简体   繁体   中英

php laravel get data on pivot table that needs joining

I'm designing a system with database like this

Companies

id
name

Employees

id
name

company_employee

company_id
employee_id
employee_role

EmployeeRole

id
name

This is to let an employee can be under many companies, with different roles. Now, query

App\\Company::find(1)->belongsToMany(Employee::class)->withPivot('employee_role')->get()

I can get something like

App\Employee {#1183
         id: 7,
         name: "John Doe",
         avatar: null,
         salary: 20000,
         insurance: 4000,
         created_at: "2018-03-28 10:15:00",
         updated_at: "2018-04-06 03:56:48",
         user_id: null,
         pivot: Illuminate\Database\Eloquent\Relations\Pivot {#1172
           company_id: 1,
           employee_id: 7,
           employee_role: 3,


           },
       },

Take a look at the pivot property, I can get their role in that specific company, but I need the role name too ( like 'Manager', or 'Sales' ). I want something like :

App\Employee {#1183
         id: 7,
         name: "John Doe",
         avatar: null,
         salary: 20000,
         insurance: 4000,
         created_at: "2018-03-28 10:15:00",
         updated_at: "2018-04-06 03:56:48",
         user_id: null,
         pivot: Illuminate\Database\Eloquent\Relations\Pivot {#1172
           company_id: 1,
           employee_id: 7,
           employee_role: 3,
**employee_role_name: "Manager"**
         },
       },

How do I do this with Eloquent? Thanks in advance

Create a pivot model:

class YourPivotModel extends \Illuminate\Database\Eloquent\Relations\Pivot {
    public function role() {
        return $this->belongsTo(EmployeeRole::class, 'employee_role');
    }
}

Use it like this:

$c->belongsToMany(Employee::class)->withPivot('employee_role')
    ->using(YourPivotModel::class)->get();

Then you can access the role name like this:

$employee->pivot->role->name

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