laravel 按created_at对Eloquent Collection排序

ezykj2lf  于 2023-10-22  发布在  其他
关注(0)|答案(4)|浏览(139)

我有一个名为'posts'的表,其中列:“post_id int primary increments”、“poster_id int”和“status text”以及一个名为friends的数组,其中列为:“user_id int primary”和“friend_ids text”。
我需要抓取朋友文本列中的所有ID,这很容易使用:

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

其中文本列中的数据看起来像'1,2,3'等。
然后我创建一个Eloquent Collection对象,这也可以通过以下方式轻松完成:

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

但问题是我不知道如何填充集合并按Post对象的'created_at'列对其内容进行排序。
这就是我目前所拥有的:

  1. foreach ($friends as $id) {
  2. $posts_ = \Post::where('poster_id', $id)->getQuery()
  3. ->orderBy('created_at', 'desc')
  4. ->get();
  5. foreach($posts_ as $post) {
  6. $posts->add($post);
  7. }
  8. }

我不知道这段代码是否能按照'created_at'列对整个帖子集合进行排序。我也需要能够轻松地分页整个集合。
收藏品分类的推荐方法是什么?

vs91vp4v

vs91vp4v1#

如果你想对一个collection进行排序,你可以使用sortBy方法通过给定的键进行排序。

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

您还可以在collection上应用回调函数

  1. $sorted = $posts->sortBy(function($post)
  2. {
  3. return $post->created_at;
  4. });

希望这对你有帮助。有关collections的更多信息,请阅读docs

3df52oht

3df52oht2#

您不需要循环遍历$friends数组,只需像这样将其与whereIn一起使用即可

  1. $posts = \Post::whereIn('poster_id', $friends)->latest()->get();

这取代了空的集合创建和foreach-循环,并将所有朋友的帖子放在一个按created_at排序的集合中

  • latest函数是orderBy('created_at', 'desc')的快捷方式)*
nvbavucw

nvbavucw3#

在Laravel 8中,分页排序可以这样实现:

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

c9x0cxw04#

如果你想获得最新添加的帖子,你可以简单地使用“反向功能”:

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

相关问题