通过created_at排序Eloquent集合 [英] Sort Eloquent Collection by created_at

查看:217
本文介绍了通过created_at排序Eloquent集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为'posts'的表,其中有'post_id int primary increment','poster_id int'和'status text'以及一个名为friends的数组:'user_id int primary'和'friend_ids文本'。



我需要抓住朋友文本列中的所有ID,这很容易使用:

  $ friends = explode(',',\Friend :: where('user_id',\Sentry :: getUser() - > id) - > first > friend_ids); 

文本列中的数据看起来像'1,2,3, / p>

然后我创建一个Eloquent集合对象,也很容易通过:

  $ posts = new \Illuminate\Database\Eloquent\Collection(); 

但问题是我不知道如何填充集合和排序其内容



这是我目前所拥有的:

 

code> 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列对整个帖子集合进行排序。我还需要能够轻松地对整个集合进行分页。



对集合进行排序的推荐方法是什么?

解决方案

如果要对集合进行排序,可以使用 sortBy 集合上应用回调函数来调用方法

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

希望这有帮助。有关 collections 的详细信息,您可以阅读文档


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?

解决方案

If you want to sort a collection you can use the sortBy method by applying a callback function on the collection

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

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

这篇关于通过created_at排序Eloquent集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆