【发布时间】:2016-01-21 04:22:34
【问题描述】:
我有一个 Post 模型,我正在尝试 ->paginate()、->groupBy() 和 ->orderBy()。
public function index()
{
$posts = Post::where('verified', '1')
->orderBy('created_at','desc')
->groupBy('topic', 'publisher_id')
->paginate(5);
// dd($posts);
}
同时,数据库中的数据如下所示:
| id | verified | topic | publisher_id | body | created_at |
| 25 | 1 | Forest | 3 | EE | 10.12.50 |
| 24 | 1 | Forest | 3 | DD | 10.11.40 |
| 23 | 1 | Forest | 3 | CC | 10.10.30 |
| 22 | 1 | Dance | 2 | BB | 9.50.50 |
| 21 | 1 | Dance | 2 | AA | 9.40.40 |
| 20 | 1 | Music | 1 | ZZ | 9.30.30 |
| 19 | 1 | Music | 1 | XX | 9.20.20 |
| 18 | 1 | Art | 1 | YY | 9.10.10 |
| 17 | 1 | Art | 1 | WW | 9.00.00 |
| 16 | 1 | Ski | 2 | KK | 7.00.00 |
当我取消注释 dd() 并运行代码时,我得到这个日志:
LengthAwarePaginator {
...
items : {
items : {
0 => Post{..}
1 => Post{..}
2 => Post{..}
3 => Post{..}
...
}
}
...
}
0 => Post{#249} : "published_by: "3", "body": "CC", "created_at": "10.10.30"
1 => Post{#250} : "published_by: "1", "body": "XX", "created_at": "9.20.20"
2 => Post{#251} : "published_by: "1", "body": "WW", "created_at": "9.00.00"
3 => Post{#252} : "published_by: "2", "body": "KK", "created_at": "7.00.00"
它看起来很奇怪是有原因的。它为用户 3 提供了groupBy,但对其他人却没有。此外,它正在拉动最早创建的而不是最晚创建的。将desc 更改为asc (如->orderBy('created_at', 'asc'))会使一切完全偏离轨道。
换句话说,返回 'CC' for user-3, Forest 而不是 'EE' for user-3, Forest
然后我想可能是 ->paginate(5) 搞砸了。
public function post()
{
$posts = Post::where...
...
->paginate(5);
$postsTry = Post::where('verified', '1')
->orderBy('created_at','desc')
->groupBy('topic', 'publisher_id')
->get();
// dd($postsTry);
}
我得到一个集合,其中只有 items 像上面的对象。
(0 => Post{..}, 1 => Post{..}, 2 => Post{..})。
它将数据分组为最早的优先,而不是最新的优先。我错过了什么?我做错了什么?
总结一下,请注意我想要得到的是:
'EE' for user-3, Forest
'BB' for user-2, Dance
'ZZ' for user-1, Music
'YY' for user-1, Art
【问题讨论】:
-
你能把
$posts->toSql();的结果贴出来吗? -
"select * from
postswhereverified=1group bytopic,publisher_idorder bycreated_atdesc"。当我在->paginate(5)->toSql();之后尝试时,它会抛出一个错误,所以我在->groupBy()之后添加了 -
GroupBy 按预期工作,它按
publisher_idANDtopic分组。由于 publisher_id 为 1 和 2 的记录涵盖多个主题,因此您最终会得到多个记录(存在的每个唯一主题的记录)。 -
那么,逻辑完全错误吗?我想做的只是为
user-3, Forest、BB for user-2, Dance等返回EE。结合相同的user_ids 和相同的主题。但相反,它为user-3, Forest返回CC -
交换
orderBy和groupBy的位置:Post::wher('verified', '1')->groupBy('topic', 'publisher_id')->orderBy('created_at', 'desc')->paginate(5)
标签: php ajax laravel pagination