【问题标题】:Laravel last news item by category idLaravel 按类别 ID 列出的最新新闻
【发布时间】:2020-12-02 03:48:21
【问题描述】:

我正在尝试了解按类别 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 |
+----+--------+-------------+-------------------------+-------------------------+

Laravel Eloquent 有没有简单的方法来做到这一点?

【问题讨论】:

标签: laravel eloquent greatest-n-per-group


【解决方案1】:

您将需要一个自加入新闻表来选择每个类别的最新新闻,例如

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

DEMO

使用查询生成器,您可以将其重写为

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-06
    • 1970-01-01
    • 2019-08-19
    • 1970-01-01
    • 2011-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多