简体   繁体   English

GroupBy和OrderBy Laravel Eloquent

[英]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. 我无法确定的是,它不是返回最后一条消息,而是应该使用orderBY对其进行排序,而是返回数据库中存在的该组的第一条记录。

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. 我发现的唯一一件事是某人的帖子,他说laravel中的orderBy和groupBy不能很好地配合使用。

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. 您可以尝试从中调用messages ,然后从中运行查询,而不是在lastMessage中重新定义关系。

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. 它将查询具有列出的链式约束的messages关系。 And by returning first() it returns only one record as opposed to a collection. 通过返回first()它仅返回一个记录,而不是一个集合。

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

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