php - Laravel 3 个模型之间的关系

标签 php laravel eloquent

我有三个模型“客户”、“任务”、“员工”。现在任务与客户相关,员工也与客户相关。但人员和任务之间没有关系。我怎样才能从一个 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/

相关文章:

php - 如何从另一个表中获取数据?这样我就可以制定条件并建立关系(Laravel + Vue)

php - vbulletin 4 搜索不起作用

javascript - TCPDF,无法在 cakephp 中包含外部 javascript 文件

Laravel 队列不在数据库中添加作业

php - 在文本框中从数据库中搜索数据以显示 - Laravel

php - Laravel Eloquent 在播种期间无人看守

javascript - 如何使用服务器端 php (Laravel) 加载其他网站,例如 Hypothes.is 或 ProjectHuddle?

php - PHP预订系统

php - 拉维尔 5.4 : how to delete a file stored in storage/app

php - Laravel 中 updateOrCreate() 和 updateOrInsert() 有什么区别