3个模型之间的拉拉维尔关系


Laravel relation between 3 models

我有三个模型客户,任务,员工。现在任务实现了客户,员工也与客户相关。但是工作人员和任务之间没有关系。如何从一个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();

在此处阅读文档:

$tasks = Task::where(...)->with('customer.staffs')->get();
// then for a given task get collection of staffs by customer:
$tasks->first()->customer->staffs;