简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM