Sort Eloquent Collection by created_at(按 created_at 对 Eloquent Collection 进行排序)
问题描述
我有一个名为 'posts' 的表,其列有:'post_id int primary increments'、'poster_id int' 和 'status text' 以及一个名为 Friends 的数组,其列是:'user_id int primary' 和 'friend_ids文本'.
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'.
我需要获取朋友文本列中的所有 ID,这很容易使用:
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);
文本列中的数据看起来像1、2、3"等
Where the data in the text column would look like '1,2,3,' etc.
然后我创建一个 Eloquent Collection 对象,这也很容易通过:
Then I create an Eloquent Collection object which is also easily done via:
$posts = new IlluminateDatabaseEloquentCollection();
但问题是我不知道如何填充集合并按 Post 对象的created_at"列对其内容进行排序.
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.
这是我目前所拥有的:
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"列对整个帖子集合进行排序.我还需要能够轻松地对整个集合进行分页.
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?
推荐答案
如果你想对 collection
进行排序,你可以使用 sortBy
方法按给定的键
If you want to sort a collection
you can use the sortBy
method by given key
$sorted = $posts->sortBy('created_at');
您也可以在 collection
$sorted = $posts->sortBy(function($post)
{
return $post->created_at;
});
希望这会有所帮助.有关 collections
的更多信息,您可以阅读 docs
Hope this helps. For more information on collections
you can read the docs
这篇关于按 created_at 对 Eloquent Collection 进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:按 created_at 对 Eloquent Collection 进行排序
基础教程推荐
- HTTP 与 FTP 上传 2021-01-01
- 使用 PDO 转义列名 2021-01-01
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01
- 如何在 XAMPP 上启用 mysqli? 2021-01-01
- PHP 守护进程/worker 环境 2022-01-01
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01