简体   繁体   English

使用 Laravel 和 MySql 获取 GROUP BY 的最后一条记录

[英]Get last record on GROUP BY using Laravel & MySql

I have two table ( users and messages ).. I wrote a query to get all messages that users sent to me or I sent, using JOIN.. to get all the users I have contacted or they did.我有两个表( usersmessages )..我写了一个查询来获取用户发送给我或我发送的所有消息,使用 JOIN.. 来获取我联系过或他们联系过的所有用户。

as in the code below:如下面的代码所示:

$users = Message::join('users',  function ($join) {
            $join->on('messages.sender_id', '=', 'users.id')
                ->orOn('messages.receiver_id', '=', 'users.id');
        })
        ->where(function ($q) {
            $q->where('messages.sender_id', Auth::user()->id)
            ->orWhere('messages.receiver_id', Auth::user()->id);
        })
        ->orderBy('messages.created', 'desc')
        ->groupBy('users.id')
        ->paginate();

The problem here is when records grouped, I'm getting the old message not the new one according to its created_at .. So, I want to get the last record of the grouped records.这里的问题是当记录分组时,我得到的是旧消息而不是新消息,根据它的created_at .. 所以,我想获得分组记录的最后一条记录。

It seems like it would make more sense to make use of Eloquent's relationships here so that you can eager load the relationships instead of having to use join and group by :在这里使用 Eloquent 的关系似乎更有意义,这样您就可以急切地加载关系,而不必使用joingroup by

$messages = Message::with('sender', 'receiver')
    ->where(function ($query) {
        $query->where('sender_id', auth()->id())
            ->orWhere('receiver_id', auth()->id())
    })
    ->orderByDesc('created') // is this meant to be 'created_at'?
    ->paginate();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM