2014-11-17 135 views
1

我有三个模型客户,任务,工作人员。现在任务是对客户实现的,而且员工与客户有关。但是人员和任务之间没有关系。我如何从一个ORM获取所有三条记录。Laravel 3个模型之间的关系

关系

/*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(); 
+1

能您可以提供更多关于表格如何相对的信息彼此相爱? – Jerodev

+0

@Jerodev我编了问题 –

回答

1

您要基于您的查询Customer,因为这是包含两种关系的模型。我相信,像这样的工作:

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

编辑

我相信这应该是可能的:

Task::where(...)->with('customer', 'customer.staffs')->get(); 
+0

如何在whereRaw('?between tasks.rem_date和tasks.due_date',[$ today])''这个工作中使用变量 –

+0

@DevAbel你试过了吗?我不明白你为什么要用'whereRaw',只用'where'? –

+0

@DevAbel你不能那样做,有单独的数据库查询,所以你不能在那里引用另一个表,除非你使用连接。 –

1

阅读文档here

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

// then for a given task get collection of staffs by customer: 
$tasks->first()->customer->staffs;