我有一个名为'posts'的表,其中列:“post_id int primary increments”、“poster_id int”和“status text”以及一个名为friends的数组,其中列为:“user_id int primary”和“friend_ids text”。
我需要抓取朋友文本列中的所有ID,这很容易使用:
$friends = explode(',', \Friend::where('user_id', \Sentry::getUser()->id)->first()->friend_ids);
其中文本列中的数据看起来像'1,2,3'等。
然后我创建一个Eloquent Collection对象,这也可以通过以下方式轻松完成:
$posts = new \Illuminate\Database\Eloquent\Collection();
但问题是我不知道如何填充集合并按Post对象的'created_at'列对其内容进行排序。
这就是我目前所拥有的:
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'列对整个帖子集合进行排序。我也需要能够轻松地分页整个集合。
收藏品分类的推荐方法是什么?
4条答案
按热度按时间vs91vp4v1#
如果你想对一个
collection
进行排序,你可以使用sortBy
方法通过给定的键进行排序。您还可以在
collection
上应用回调函数希望这对你有帮助。有关
collections
的更多信息,请阅读docs3df52oht2#
您不需要循环遍历
$friends
数组,只需像这样将其与whereIn一起使用即可这取代了空的集合创建和
foreach
-循环,并将所有朋友的帖子放在一个按created_at
排序的集合中latest
函数是orderBy('created_at', 'desc')
的快捷方式)*nvbavucw3#
在Laravel 8中,分页排序可以这样实现:
c9x0cxw04#
如果你想获得最新添加的帖子,你可以简单地使用“反向功能”: