我有一个名为“posts”的表,其中包含以下列:“post_id intprimary Increments”、“poster_id int”和“status text”,以及一个名为“friends”的数组,其中包含以下列:“user_id int Primary”和“friend_ids text” .
我需要获取好友文本列中的所有 ID,这很容易使用:
$friends = explode(',', \Friend::where('user_id', \Sentry::getUser()->id)->first()->friend_ids);
文本列中的数据看起来像“1,2,3”等。
然后我创建一个 Eloquent Collection 对象,这也可以通过以下方式轻松完成:
$posts = new \Illuminate\Database\Eloquent\Collection();
但问题是我不知道如何填充集合并按 Post 对象的“created_at”列对其内容进行排序。
这就是我现在所拥有的:
foreach ($friends as $id) {
$posts_ = \Post::where('poster_id', $id)->getQuery()
->orderBy('created_at', 'desc')
->get();
foreach($posts_ as $post) {
$posts->add($post);
}
}
我不知道这段代码是否适用于按“created_at”列对整个帖子集合进行排序。我还需要能够轻松地对整个集合进行分页。
推荐的集合排序方式是什么?
如果你想对
collection
进行排序,你可以通过给定的键使用 sortBy
方法
$sorted = $posts->sortBy('created_at');
您还可以在
collection
上应用回调函数
$sorted = $posts->sortBy(function($post)
{
return $post->created_at;
});
希望这有帮助。有关
collections
的更多信息,您可以阅读 docs
你不需要循环遍历
$friends
数组,你可以像这样将它与 whereIn 一起使用
$posts = \Post::whereIn('poster_id', $friends)->latest()->get();
这取代了空集合创建和
foreach
循环,并为您提供一个集合中所有朋友的帖子,并按 created_at
排序
(
latest
功能是orderBy('created_at', 'desc')
的快捷方式)
在 Laravel 8 中可以这样实现分页排序:
$sorted = $posts->sortBy('created_at');
如果您想获取最新添加的帖子,只需使用“反向功能”即可:
$sorted = $posts->sortBy('created_at')->reverse();