繁体   English   中英

GroupBy和OrderBy Laravel Eloquent

[英]GroupBy and OrderBy Laravel Eloquent

使用仪表板构建聊天应用程序,并尝试获取该其他用户发送的最后一条消息的通知。

这是我的模型关系:

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');
}

我无法确定的是,它不是返回最后一条消息,而是应该使用orderBY对其进行排序,而是返回数据库中存在的该组的第一条记录。

在网上四处张望,但似乎找不到任何信息。 我发现的唯一一件事是某人的帖子,他说laravel中的orderBy和groupBy不能很好地配合使用。

任何帮助表示赞赏!

您可以尝试从中调用messages ,然后从中运行查询,而不是在lastMessage中重新定义关系。

没有看到更多的模型模式(即:这些关系在哪里定义??),这可能并不完美,但这只是一个开始:

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

它将查询具有列出的链式约束的messages关系。 通过返回first()它仅返回一个记录,而不是一个集合。

暂无
暂无

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

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