使用嵌套子句对查询结果进行排序

时间:2019-08-08 09:10:54

标签: mysql sql laravel eloquent

我正在为我的Laravel应用使用此数据库表:

| id | description | status   | timestamp  |
|----|-------------|----------|------------|
| 1  | Lorem ipsum | pending  | 2019-08-01 |
| 2  | Lorem ipsum | approved | 2019-08-01 |
| 3  | Lorem ipsum | pending  | 2019-08-01 |
| 4  | Lorem ipsum | approved | 2019-08-01 |
| 5  | Lorem ipsum | review   | 2019-08-01 |
| 6  | Lorem ipsum | review   | 2019-08-01 |
| 7  | Lorem ipsum | closed   | 2019-08-01 |
| 8  | Lorem ipsum | pending  | 2019-08-01 |
| 9  | Lorem ipsum | approved | 2019-08-01 |
...

此表所需的排序逻辑是:

pending > review > approved > closed

然后,每个子组必须按

排序
id, DESC

所以期望的结果应该是:

| id | description | status   | timestamp  |
|----|-------------|----------|------------|
| 8  | Lorem ipsum | pending  | 2019-08-01 |
| 3  | Lorem ipsum | pending  | 2019-08-01 |
| 1  | Lorem ipsum | pending  | 2019-08-01 |
| 6  | Lorem ipsum | review   | 2019-08-01 |
| 5  | Lorem ipsum | review   | 2019-08-01 |
| 9  | Lorem ipsum | approved | 2019-08-01 |
| 4  | Lorem ipsum | approved | 2019-08-01 |
| 2  | Lorem ipsum | approved | 2019-08-01 |
| 7  | Lorem ipsum | closed   | 2019-08-01 |
...

我试图使用这个雄辩的查询:

$posts = Post::orderByRaw( "FIELD(status, 'pending', 'review', 'approved', 'closed')" )
         ->groupBy('id')
         ->paginate(5)
         ->toJson();

但是,ID顺序是递增的:

| id | description | status   | timestamp  |
|----|-------------|----------|------------|
| 1  | Lorem ipsum | pending  | 2019-08-01 |
| 3  | Lorem ipsum | pending  | 2019-08-01 |
| 8  | Lorem ipsum | pending  | 2019-08-01 |
| 5  | Lorem ipsum | review   | 2019-08-01 |
| 6  | Lorem ipsum | review   | 2019-08-01 |
| 2  | Lorem ipsum | approved | 2019-08-01 |
| 4  | Lorem ipsum | approved | 2019-08-01 |
| 9  | Lorem ipsum | approved | 2019-08-01 |
| 7  | Lorem ipsum | closed   | 2019-08-01 |
...

我不知道如何在具有状态分组的每个子结果中首先对具有较大ID的行进行排序。

1 个答案:

答案 0 :(得分:2)

您在ID上使用groupBy()而不是orderBy()。您可以在, id DESC方法中添加orderByRaw(),也可以在orderBy('id', 'desc')方法中添加groupBy()

在这种情况下,使用groupBy('id')毫无意义,因为它的独特性。

$posts = Post::orderByRaw( "FIELD(status, 'pending', 'review', 'approved', 'closed')" )
             ->orderBy('id', 'desc')
             ->paginate(5)
             ->toJson();