简体   繁体   中英

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.

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.

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 :

$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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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