Order By before Group By using Eloquent (Laravel)(Order By before Group By 使用 Eloquent (Laravel))
问题描述
我有一个包含以下列的消息"表
I have a "messages" table with the following columns
CREATE TABLE `messages` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`fromId` int(11) NOT NULL,
`toId` int(11) NOT NULL,
`message` text NOT NULL,
`status` int(11) NOT NULL,
`device` varchar(100) NOT NULL,
`createdAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=57 DEFAULT CHARSET=latin1;
我正在尝试获取所有 'toId' = $id 并按 fromId 分组的消息.问题是结果中显示的消息"是第一个,而不是最新的.我尝试通过 createdAt 订购,但它不起作用.
I'm trying to get all messages where 'toId' = $id and grouping by fromId. The problem is that the "message" shown on the results is the first ones, not the latest ones. I tried ordering by createdAt but it's not working.
如何在查询和分组结果之前按createdAt"排序?我想使用 Eloquent 以 laravel 的方式做到这一点.
How can I order by "createdAt" prior to querying and grouping the results? I want to do this in the laravel way using Eloquent.
我的查询:
$chats = Message::with('sender','recipient')
->where('toId',$id)
->orderBy('createdAt')
->groupBy('fromId')
->paginate(10)
推荐答案
我找到了一种方法!基本上,创建一个子查询并在之前运行它,以便结果按预期排序并在其后分组.
I found a way to do that! Basically, creating a subquery and running it before, so that results are ordered as expected and grouped after.
代码如下:
$sub = Message::orderBy('createdAt','DESC');
$chats = DB::table(DB::raw("({$sub->toSql()}) as sub"))
->where('toId',$id)
->groupBy('fromId')
->get();
这篇关于Order By before Group By 使用 Eloquent (Laravel)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Order By before Group By 使用 Eloquent (Laravel)
基础教程推荐
- HTTP 与 FTP 上传 2021-01-01
- PHP 守护进程/worker 环境 2022-01-01
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01
- 使用 PDO 转义列名 2021-01-01
- 如何在 XAMPP 上启用 mysqli? 2021-01-01
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01