Skip to content
Advertisement

Adding additional column to the result of relationship in eloquent

I have two models. Both of them are pivots because they join other tables. But also they have a relationship with themselves.

class CompanyUser extends Pivot
{
    protected $table = 'company_user';

    public function companyUserProducts() {
        return $this->hasMany('AppCompanyUserProduct','company_user_id');
    }

}

class CompanyUserProduct extends Pivot
{
    protected $table = 'company_user_product';

    public function companyUser() {
        return $this->belongsTo('AppCompanyUser','company_user_id');
    }
    
}

I want to get all entities of CompanyUserProduct but with the additional column user_id from CompanyUser, so I can do pluck('user_id') on the collection and get all IDs at once. Is it possible to do it in Eloquent, or must I use Query Builder?

$companyUsers = CompanyUserProduct::with('companyUser')->get();

Advertisement

Answer

You can do

$companyUsers = CompanyUserProduct::with('companyUser:id,user_id')->get();

To retrieve the CompanyUserProduct along with the id and user_id of compantUser.

Note: whatever your primary key for companyUser – make sure you select it as well. (In this case assumed to be id)

Once you retrieve the collection, the user_id will be under companyUser for each CompanyUserProduct

So, you can pluck it using dot notation.

eg:

$userIds = $companyUsers->pluck('companyUser.user_id');
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement