Alexxosipov
Alexxosipov

Reputation: 1234

How to get 3 items from the pivot table via Eloquent (Laravel)?

A bit of business logic: 1 company may have many users with different roles. 1 user may have only 1 role in company.

In the database I have a pivot table company_user_roles. There're 3 fields: company_id, user_id, role_id. Then I have a User model and belongsToMany relation for getting user's companies:

public function companies()
    {
        return $this->belongsToMany(
         'App\Company', 
         'company_user_roles', 
         'user_id', 
         'company_id'
        );
    }

$user->companies returns a collection of companies. But there's no user's role in each company. I have only this for each company (and it seems to be expected):

#attributes: array:4 [▼
        "id" => 1
        "name" => "Company name"
        "created_at" => "2018-07-08 15:45:40"
        "updated_at" => "2018-07-08 15:45:42"
]

But I don't understand how to get a role of the user for each company. I want to get something like this:

#attributes: array:4 [▼
            "id" => 1
            "name" => "Company name"
            "role" => [
              "id": 1,
              "name": "owner"
            ]
            "created_at" => "2018-07-08 15:45:40"
            "updated_at" => "2018-07-08 15:45:42"
    ]

Or something like this, but without extra queries to the database. How to implement this logic in this case?

Upvotes: 1

Views: 896

Answers (1)

rkj
rkj

Reputation: 8297

There is one solution to add belongsTo relation in your pivot model CompanyUserRole but then you can't load that belongsTo relation from your pivot using eager loading. The second solution is to use hasMany relationship, when you have more than 2 foreign key in pivot table.

User Model

public function roleUserCompanies(){
    return $this->hasMany('App\CompanyUserRole'); 
}

Company Model

public function roleCompanyUsers(){
    return $this->hasMany('App\CompanyUserRole'); 
}

CompanyUserRole Model

class CompanyUserRole extends Model {
    protected $table = 'company_user_roles';

    public function company(){
       return $this->belongsTo('App\Company');
    }

    public function user(){
       return $this->belongsTo('App\User');
    }


    public function role(){
       return $this->belongsTo('App\Role');
    }
}

Fetch data

$user = User::with('roleUserCompanies', 'roleUserCompanies.company', 'roleUserCompanies.role')->find(1);

foreach($user->roleUserCompanies as $roleUserCompany){
    dd($roleUserCompany->company);
    dd($roleUserCompany->role);
}

Hope this may help you

Upvotes: 1

Related Questions