我有三个模型“客户”、“任务”、“员工”。现在任务与客户相关,员工也与客户相关。但人员和任务之间没有关系。我怎样才能从一个 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();
最佳答案
您希望将查询基于 Customer
,因为这是包含这两种关系的模型。我相信这样的事情会起作用:
Customer::with('staffs', 'tasks')->where('tasks.field', $value)->get();
编辑
我相信这也应该是可能的:
Task::where( ... )->with('customer', 'customer.staffs')->get();
关于php - Laravel 3 个模型之间的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26969458/