我正在设计一个像这样的数据库系统
公司
SELECT T1.val,CASE WHEN T2.val IS NULL THEN 0 ELSE 1 END as [New]
FROM
T AS T1
LEFT JOIN
(
SELECT val,COUNT(1) 'totle'
FROM T
GROUP BY val
) AS T2 ON T2.totle > 1 and t1.val = t2.val
员工
id
name
company_employee
id
name
EmployeeRole
company_id
employee_id
employee_role
这是为了让员工可以在不同角色的许多公司之下。 现在,查询
id
name
我可以得到像
这样的东西App\Company::find(1)->belongsToMany(Employee::class)->withPivot('employee_role')->get()
看一下pivot属性,我可以在该特定公司中获得他们的角色,但我也需要角色名称(例如'经理'或'销售')。我想要这样的东西:
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,
},
},
我如何用Eloquent做到这一点? 提前致谢
答案 0 :(得分:1)
创建枢轴模型:
class YourPivotModel extends \Illuminate\Database\Eloquent\Relations\Pivot {
public function role() {
return $this->belongsTo(EmployeeRole::class, 'employee_role');
}
}
像这样使用:
$c->belongsToMany(Employee::class)->withPivot('employee_role')
->using(YourPivotModel::class)->get();
然后您可以像这样访问角色名称:
$employee->pivot->role->name