Laravel relation between 3 models

2019-08-03 06:06发布

I have three models Customer, Task, Staffs. Now task is realted to customer and also staff is related to customer. But there is no relation between staff and task. How can i get all the three records from one ORM.

relationship

/*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');
}

I have tasks filtered by dates already. I need its customers and the staffs related to those customers.

$tasks = Task::Where(...)->with('customer')->with('staffs')->get();

2条回答
三岁会撩人
2楼-- · 2019-08-03 06:38

You want to base your query on Customer since this is the model containing both relations. I believe something like this would work:

Customer::with('staffs', 'tasks')->where('tasks.field', $value)->get();

Edit

I believe this should be possible as well:

Task::where( ... )->with('customer', 'customer.staffs')->get();
查看更多
▲ chillily
3楼-- · 2019-08-03 06:57

Read the docs here:

$tasks = Task::where(...)->with('customer.staffs')->get();

// then for a given task get collection of staffs by customer:
$tasks->first()->customer->staffs;
查看更多
登录 后发表回答