Laravel雄辩的加入,但仅显示关系中的最大行 [英] Laravel Eloquent Join but only show max row from relationship

查看:49
本文介绍了Laravel雄辩的加入,但仅显示关系中的最大行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个模型客户联系人,它们具有以下关系:

I have two Models Customer, Contact with the following relation:

// 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

现在,我想创建一个包含所有客户列表的视图,包括每个客户的最新联系人,每个客户仅一行.看起来应该像这样:

Now I want to create a view with a list of all my customers including the latest contact per customer with only one row per customer. It shall look something like this:

Customer ID | Name | Last Contact Date
1           | John | 2018-01-03
2           | Max  | 2018-01-01
...         | ...  | ...

我已经尝试通过类似的方式实现这一目标

I already tried to achieve this with something like

// Customer Model
public function contactsList () {
    return $this->contacts()
                ->leftJoin('contacts', 'customers.id', '=', 'contacts.customer_id')
                ->groupBy('customer.id')
                ->orderByRaw('contacts.created_at desc');
}

但这不是我所期望的.有人可以帮我吗?

but it's not what I expected. Can someone help me with this?

非常感谢!

推荐答案

要使其正常运行,您需要创建新的hasOne() Customer模型中的关系:

To make it work you need to create a new hasOne() relationship in Customer model:

public function latestContact()
{
    return $this->hasOne(Contact::class)->latest();
}

然后使用它:

$customersWithLatestContact = Customer::with('latestContact')->get();

这篇关于Laravel雄辩的加入,但仅显示关系中的最大行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆