Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
663 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...