我有三个模型Customer,Task,Staffs。现在任务已经完成给客户,员工也与客户有关。但是员工和任务之间没有关系。如何从一个ORM中获取所有三个记录。
关系
/*staff*/ /**have pivot table 'staff_customer' **/
public function customers(){
return $this->belongsToMany('Customer');
}
/*customer*/
public function staffs(){
return $this->belongsToMany('Staff');
}
public function tasks(){
return $this->hasMany('Task');
}
/*task*/ /** has cutomer_id in table*/
public function customer(){
return $this->belongsTo('Customer');
}
我已经按日期过滤了任务。我需要客户和与这些客户相关的员工。
$tasks = Task::Where(...)->with('customer')->with('staffs')->get();
答案 0 :(得分:1)
您希望将查询基于Customer
,因为这是包含两种关系的模型。我相信这样的事情会奏效:
Customer::with('staffs', 'tasks')->where('tasks.field', $value)->get();
修改的
我相信这也应该是可能的:
Task::where( ... )->with('customer', 'customer.staffs')->get();
答案 1 :(得分:1)
阅读文档here:
$tasks = Task::where(...)->with('customer.staffs')->get();
// then for a given task get collection of staffs by customer:
$tasks->first()->customer->staffs;