Sort Eloquent Collection by created_at

时光怂恿深爱的人放手 提交于 2019-12-21 06:53:08

问题


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'.

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);

Where the data in the text column would look like '1,2,3,' etc.

Then I create an Eloquent Collection object which is also easily done via:

$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.

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.

What is the recommended way of sorting the collection?


回答1:


If you want to sort a collection you can use the sortBy method by given key

$sorted = $posts->sortBy('created_at');

Also you can apply a callback function on the collection

$sorted = $posts->sortBy(function($post)
{
  return $post->created_at;
});

Hope this helps. For more information on collections you can read the docs




回答2:


You don't need to loop through the $friends array, you can just use it together with whereIn like this

$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

(the latest function is a shortcut for orderBy('created_at', 'desc'))



来源:https://stackoverflow.com/questions/20818858/sort-eloquent-collection-by-created-at

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!