php 按 created_at 对 Eloquent Collection 进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20818858/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sort Eloquent Collection by created_at
提问by Liam Potter
I have a table named 'posts' with the columns: 'post_id int primary increments', 'poster_id int' and 'status text' as well as an array named friends with the columns: 'user_id int primary' and 'friend_ids text'.
我有一个名为 'posts' 的表,其列有:'post_id int primary increments'、'poster_id int' 和 'status text' 以及一个名为 Friends 的数组,其中包含以下列:'user_id int primary' 和 'friend_ids text'。
I need to grab all the IDs in the friends text column which is easy enough using:
我需要获取朋友文本列中的所有 ID,这很容易使用:
$friends = explode(',', \Friend::where('user_id', \Sentry::getUser()->id)->first()->friend_ids);
Where the data in the text column would look like '1,2,3,' etc.
文本列中的数据看起来像“1,2,3”等。
Then I create an Eloquent Collection object which is also easily done via:
然后我创建了一个 Eloquent Collection 对象,它也可以通过以下方式轻松完成:
$posts = new \Illuminate\Database\Eloquent\Collection();
But the problem is I can't figure out how to populate the collection and sort its contents by the Post object's 'created_at' column.
但问题是我不知道如何填充集合并按 Post 对象的“created_at”列对其内容进行排序。
This is what I have at the moment:
这就是我目前所拥有的:
foreach ($friends as $id) {
$posts_ = \Post::where('poster_id', $id)->getQuery()
->orderBy('created_at', 'desc')
->get();
foreach($posts_ as $post) {
$posts->add($post);
}
}
I can't figure out if this code would work or not for sorting the entire collection of posts by the 'created_at' column. I would also need to be able to paginate the entire collection easily.
我不知道此代码是否适用于按“created_at”列对整个帖子集合进行排序。我还需要能够轻松地对整个集合进行分页。
What is the recommended way of sorting the collection?
推荐的集合排序方式是什么?
回答by Altrim
If you want to sort a collectionyou can use the sortBymethod by given key
如果要对 a 进行排序collection,可以sortBy按给定的键使用该方法
$sorted = $posts->sortBy('created_at');
Also you can apply a callback function on the collection
您也可以在 collection
$sorted = $posts->sortBy(function($post)
{
return $post->created_at;
});
Hope this helps. For more information on collectionsyou can read the docs
希望这可以帮助。有关更多信息,collections您可以阅读文档
回答by Arvid
You don't need to loop through the $friendsarray, you can just use it together with whereInlike this
您不需要遍历$friends数组,您可以像这样将它与whereIn一起使用
$posts = \Post::whereIn('poster_id', $friends)->latest()->get();
This replaces the empty collection creation and the foreach-loop, and gives you all your friends posts in one Collection sorted by created_at
这取代了空集合创建和 -foreach循环,并为您提供一个集合中的所有朋友帖子,按以下顺序排序created_at
(the latestfunction is a shortcut for orderBy('created_at', 'desc'))
(该latest函数是 的快捷方式orderBy('created_at', 'desc'))

