按组排序使用Eloquent(Laravel)

时间:2015-08-06 14:08:13

标签: php laravel eloquent

我有一条"消息"具有以下列的表

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;

我试图将所有邮件发送到#Id' = $ id和fromId分组。问题是"消息"结果显示的是第一个,而不是最新的。我尝试通过createdAt订购,但它没有用。

我如何通过" createdAt"在查询和分组结果之前?我想用Eloquent以laravel方式做到这一点。

我的查询:

$chats = Message::with('sender','recipient')
        ->where('toId',$id)
        ->orderBy('createdAt')
        ->groupBy('fromId')
        ->paginate(10)

6 个答案:

答案 0 :(得分:22)

我只需要做一些与消息模型类似的事情。对我有用的是在返回的eloquent集合上应用unique方法。

Model::where('toId', $id)
    ->orderBy('createdAt', 'desc')
    ->get()
    ->unique('fromId');

查询将返回createdAt订购的所有邮件,而unique方法会将其减少为每个fromId的一封邮件。这显然不如直接使用数据库那样高效,但在我的情况下,我对查询有进一步的限制。

此外,还有许多有用的方法可以处理这些集合:https://laravel.com/docs/5.2/collections#available-methods

答案 1 :(得分:5)

我找到了办法!基本上,创建一个子查询并在之前运行它,以便结果按预期排序并在之后分组。

以下是代码:

$sub = Message::orderBy('createdAt','DESC');

$chats = DB::table(DB::raw("({$sub->toSql()}) as sub"))
    ->where('toId',$id)
    ->groupBy('fromId')
    ->get();

答案 2 :(得分:2)

这项工作对我来说: (您可以通过createdAt删除订单,以防createAt与id一起增加)

dispatch_async

答案 3 :(得分:1)

应该是这样的:

Message::whereToId($id)->groupBy('fromId')->latest('createdAt')->first();

<强>更新

在看到您添加的查询后,您可能只需要向orderBy函数添加方向,如下所示:

$chats = Message::with('sender','recipient')
    ->select(DB::raw('*, max(createdAt) as createdAt'))
    ->where('toId',$id)
    ->orderBy('createdAt', 'desc')
    ->groupBy('fromId')
    ->paginate(10)

答案 4 :(得分:0)

尝试此查询:

$chats = Message::with('sender','recipient')
->where('toId',$id)
->whereRaw('id IN (select MAX(id) FROM messages GROUP BY fromId)')
->orderBy('createdAt','desc')
->paginate(10)

答案 5 :(得分:0)

 $data = MCCAddMilkEntry::where('coming_from','=','society')
        ->whereRaw('id = (select max(`id`) from mcc_add_milk_entry)')->get();