我有一个名为“ 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'列对整个帖子集进行排序。我还需要能够轻松对整个集合进行分页。
建议对集合进行排序的方式是什么?
如果要排序collection
,可以sortBy
按给定键使用方法
$sorted = $posts->sortBy('created_at');
您也可以在 collection
$sorted = $posts->sortBy(function($post)
{
return $post->created_at;
});
希望这可以帮助。有关更多信息,collections
您可以阅读文档
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句