【问题标题】:Laravel Eloquent Join but only show max row from relationshipLaravel Eloquent Join,但仅显示关系中的最大行
【发布时间】: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');
}

但这不是我所期望的。有人可以帮我解决这个问题吗?

非常感谢!

【问题讨论】:

    标签: laravel join eloquent


    【解决方案1】:

    要使其正常工作,您需要在 Customer 模型中使用 create a new hasOne() relationship

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

    然后使用它:

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

    【讨论】:

    • 谢谢。这比预期的要容易得多。还有一件事:如何处理还没有联系的客户?对于那些我收到以下错误的人:“尝试获取非对象的属性”
    • @maxiw46 在显示数据时使用optional() 帮助器optional($customer->latestContact)->address 或使用@if (!empty($customer->latestContact)) 手动检查它
    • 效果很好!非常感谢!
    猜你喜欢
    • 2020-07-31
    • 2017-07-18
    • 1970-01-01
    • 2015-10-14
    • 2021-12-13
    • 2021-12-24
    • 2016-05-19
    • 2021-12-05
    • 1970-01-01
    相关资源
    最近更新 更多