问题描述
我正在尝试按类别ID归纳最新新闻。
示例数据:
+----+--------+-------------+-------------------------+-------------------------+
| id | title | category_id | created_at | updated_at |
+----+--------+-------------+-------------------------+-------------------------+
| 1 | Item 1 | 1 | 2020-08-01 12:00:00.000 | 2020-08-01 12:00:00.000 |
| 2 | Item 2 | 2 | 2020-08-02 12:00:00.000 | 2020-08-02 12:00:00.000 |
| 3 | Item 3 | 4 | 2020-08-02 12:00:00.000 | 2020-08-02 12:00:00.000 |
| 4 | Item 4 | 1 | 2020-08-04 12:00:00.000 | 2020-08-04 12:00:00.000 |
| 5 | Item 5 | 2 | 2020-08-11 12:00:00.000 | 2020-08-11 12:00:00.000 |
+----+--------+-------------+-------------------------+-------------------------+
我想要输出:
+----+--------+-------------+-------------------------+-------------------------+
| id | title | category_id | created_at | updated_at |
+----+--------+-------------+-------------------------+-------------------------+
| 3 | Item 3 | 4 | 2020-08-02 12:00:00.000 | 2020-08-02 12:00:00.000 |
| 4 | Item 4 | 1 | 2020-08-04 12:00:00.000 | 2020-08-04 12:00:00.000 |
| 5 | Item 5 | 2 | 2020-08-11 12:00:00.000 | 2020-08-11 12:00:00.000 |
+----+--------+-------------+-------------------------+-------------------------+
解决方法
您将需要自动加入新闻列表,以选择每个类别的最新新闻,例如
select n.*
from news n
left join news n1 on n.category_id = n1.category_id
and n.created_at < n1.created_at
where n1.category_id is null
使用查询生成器,您可以将其重写为
DB::table('news as n')
->select('n.*')
->leftJoin('news as n1',function ($join) {
$join->on('n.category_id','=','n1.category_id')
->whereRaw(DB::raw('n.created_at < n1.created_at'));
})
->whereNull('n1.category_id')
->get();