Reputation: 45
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
Upvotes: 0
Views: 449
Reputation: 25906
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
Upvotes: 1