简体   繁体   中英

GroupBy and OrderBy Laravel Eloquent

Building a chat application with a dashboard and am trying to get a notification of the last message the that other user sent.

Here is my Model relationships:

public function messages() {
    return $this->hasMany('App\Message', 'author_id');
}

public function lastMessage() {
    return $this->hasMany('App\Message', 'recipient_id')->orderBy('created_at', 'DESC')->groupBy('author_id');
}

On thing I cant figure out is instead of returning the last message as it should be sorted by using orderBY, it returns the first record of that group that exists in the database.

Looked around online but cant seem to find any info on this. The only thing I found is a post by someone who said that orderBy and groupBy in laravel don't play well together.

Any help is appreciated!

Instead of redefining the relationship in lastMessage , you might try calling messages from it and then running your query from that.

Without seeing more of your model schema (ie: where are these relationships defined??), this might not be perfect, but it's a start:

public function lastMessage()
{
    return $this->messages() // <-- Notice the ()...this creates a query instead of immediately returning the relationship
        ->where('recipient_id', $this->id) // Not sure if this is correct, might need to adjust according to how you have defined the tables
        ->orderBy('created_at', 'desc')
        ->first();
}

It will query the messages relationship with the chained constraints that are listed. And by returning first() it returns only one record as opposed to a collection.

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