【发布时间】:2018-07-27 02:22:13
【问题描述】:
我有两个模型客户,联系人具有以下关系:
// Customer Model
public function contacts() {
return $this->hasMany('Contact', 'customer_id')
}
联系人如下所示:
id | created_at | body | customer_id
1 | 2018-01-03 | text | 1
2 | 2018-01-01 | text | 2
3 | 2017-12-25 | text | 1
4 | 2017-10-13 | text | 2
5 | 2017-10-03 | text | 2
现在我想创建一个视图,其中包含我所有客户的列表,包括每个客户的最新联系人,每个客户只有一行。它应该看起来像这样:
Customer ID | Name | Last Contact Date
1 | John | 2018-01-03
2 | Max | 2018-01-01
... | ... | ...
我已经尝试过用类似的方法来实现这一点
// Customer Model
public function contactsList () {
return $this->contacts()
->leftJoin('contacts', 'customers.id', '=', 'contacts.customer_id')
->groupBy('customer.id')
->orderByRaw('contacts.created_at desc');
}
但这不是我所期望的。有人可以帮我解决这个问题吗?
非常感谢!
【问题讨论】: