問題描述
我有一個名為 'posts' 的表,其列有:'post_id int primary increments'、'poster_id int' 和 'status text' 以及一個名為 Friends 的數(shù)組,其列是:'user_id int primary' 和 'friend_ids文本'.
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'.
我需要獲取朋友文本列中的所有 ID,這很容易使用:
I need to grab all the IDs in the friends text column which is easy enough using:
$friends = explode(',', Friend::where('user_id', Sentry::getUser()->id)->first()->friend_ids);
文本列中的數(shù)據(jù)看起來像1、2、3"等
Where the data in the text column would look like '1,2,3,' etc.
然后我創(chuàng)建一個 Eloquent Collection 對象,這也很容易通過:
Then I create an Eloquent Collection object which is also easily done via:
$posts = new IlluminateDatabaseEloquentCollection();
但問題是我不知道如何填充集合并按 Post 對象的created_at"列對其內(nèi)容進行排序.
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.
這是我目前所擁有的:
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"列對整個帖子集合進行排序.我還需要能夠輕松地對整個集合進行分頁.
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.
推薦的集合排序方式是什么?
What is the recommended way of sorting the collection?
推薦答案
如果你想對 collection
進行排序,你可以使用 sortBy
方法按給定的鍵
If you want to sort a collection
you can use the sortBy
method by given key
$sorted = $posts->sortBy('created_at');
您也可以在 collection
$sorted = $posts->sortBy(function($post)
{
return $post->created_at;
});
希望這會有所幫助.有關(guān) collections
的更多信息,您可以閱讀 docs
Hope this helps. For more information on collections
you can read the docs
這篇關(guān)于按 created_at 對 Eloquent Collection 進行排序的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!