我有一个包含以下列的"消息"表

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;

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.

How can I order by "createdAt" prior to querying and grouping the results? I want to do this in the laravel way using Eloquent.

My query:

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

Laravel相关问答推荐

灯丝:设定模式标题

在没有lang/*.json文件的情况下在Laravel项目中实现多语言支持

我是否需要/是否可以从控制器运行LARLAVEL备份?

如何在使用Docker容器部署Laravel 8、9、10时处理SIGTERM信号,特别是与调度程序和工作进程相关的问题?

Laravel REST API:如何将数据库列名与参数的另一个名称映射?

工厂多对多数据透视表属性

如何通过 Controller 访问 Laravel 中 Model 的值?

如何获得每种类型的总和

Laravel 5 Eloquent 范围连接并 Select 特定列

使用 Eloquent (Laravel) 在 Group By 之前排序

转储或 dd laravel 在结果前添加字符时出错

Twilio 查找 API 不起作用?

laravel 5中的配置缓存导致找不到视图

将非框架 PHP 项目移植到 Laravel 4.x

如何在包中安排 Artisan 命令?

Laravel 5 - 为包创建 Artisan 命令

无法打开laravel.log:无法打开流

laravel 如何读取 app/config/app.php 调试变量

Laravel 5.4 - Mix - 如何运行浏览器实时重新加载

Carbon解析到 ISO8601