【问题标题】:Laravel grouping and ordering database resultsLaravel 分组排序数据库结果
【发布时间】:2020-05-06 17:05:14
【问题描述】:

假设我有下表...

+----+---------------------+---------+---------------------+
| id | slug                | version | created_at          |
+----+---------------------+---------+---------------------+
| 1  | url-friendly-string | 1.0.0   | 2020-01-19 01:00:00 |
+----+---------------------+---------+---------------------+
| 2  | url-friendly-string | 1.0.0   | 2020-01-19 02:00:00 |
+----+---------------------+---------+---------------------+
| 3  | url-friendly-string | 1.0.1   | 2020-01-20 00:00:00 |
+----+---------------------+---------+---------------------+
| 4  | another             | 0.0.1   | 2020-01-20 00:30:00 |
+----+---------------------+---------+---------------------+
| 5  | another             | 0.0.2   | 2020-01-20 01:00:00 |
+----+---------------------+---------+---------------------+

可以有多个具有相同slugversion 的条目,我想获得按slug 分组的每个项目的最新、最高版本。例如,最终结果看起来有点像……

$collection = Array(
    Object(
        'slug' => 'another',
        'version' => '0.0.2',
        'created_at' => '2020-01-20 01:00:00'
    ),
    Object(
        'slug' => 'url-friendly-string',
        'version' => '1.0.1',
        'created_at' => '2020-01-20 00:00:00'
    )
)

我已经尝试了以下...

1.

$collection = auth()->user()
    ->items()
    ->orderBy('created_at', 'desc')
    ->orderBy('version', 'desc')
    ->groupBy('slug', 'version')
    ->get();

产生:

语法错误或访问冲突:1055 SELECT 列表的表达式 #1 不在 GROUP BY 子句中并且包含非聚合列

可以在此处找到有关此错误的一个很好的答案:https://stackoverflow.com/a/36230200/3804924

2.

$collection = auth()->user()
    ->items()
    ->orderBy('created_at', 'desc')
    ->orderBy('version', 'desc')
    ->get()
    ->groupBy('slug', 'version')
    ->map(function($group) {
        return $group->first();
    });

哪种有效但会产生错误的排序。


我怎样才能到达我需要去的地方?

这是一个新项目,因此破坏表等不是问题。

【问题讨论】:

  • 不正确的排序是什么意思?

标签: php sql laravel eloquent laravel-6


【解决方案1】:

您可以先通过子查询对表进行排序,试试这个:

$subSql = DB::table('my_table')->orderBy('version', 'desc')->toSql();

$result = DB::table( DB::raw("({$subSql}) as subQuery") )
    ->groupBy('slug')
    ->get();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 2023-03-19
    • 2011-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多