雄辩地对数据进行排序 [英] Sorting data with Eloquent
问题描述
我是laravel的新手(从CI转换过来),而雄辩的ORM在某些时候还是个谜!
I'm new to laravel (switched from CI) and eloquent ORM is still a bit of a mystery at some point!
这是我的问题:
我想使用Eloquent对数据库中的数据进行排序.
I'd like to sort data from my db using Eloquent.
我有一个表帖子和一个表评论(帖子有很多评论,评论属于帖子)
I have a table posts and a table comments (post has many comments and comment belongs to posts)
每个评论都有一个时间戳(=> created_at字段),我想按以下顺序进行排序:
Every comment has a timestamp (=> created_at field) and I'd like to order things as follow :
(我们在配置文件页面上,因此$ user-> id是用户的ID(显然))
(we're on profil page so $user->id is the id of the user (obviously))
我希望该用户发表评论的帖子中的所有帖子,并通过评论的created_at字段对所有帖子进行排序
我真的很想完整地使用Eloquent,或者至少要使用Fluent,我不知道正确的使用方法.
I really want to use Eloquent fully, or at least Fluent, and I don't know the right way to do so.
我希望我很清楚,谢谢您的宝贵时间!
I hope I'm being clear, and thank you for your time!
推荐答案
我刚在开发的项目中遇到了同样的问题.在我到处看的地方,我都将usort()
或uasort()
作为解决此问题的建议方法. ( Collection::sort()
只是uasort()
的包装器),但不能满足要求我,因为为什么当SQL应该使用ORDER BY子句为我执行SQL时,为什么要使用PHP进行排序?我最终使用getXXXAttribute()方法以这种方式实现它:
I just ran into the same problem on a project I am developing. Everywhere I looked I saw the usort()
or uasort()
as the suggested way to solve this problem. (Collection::sort()
is just a wrapper for uasort()
) but that did not satisfy me because why would I use PHP to sort when SQL should do it for me with an ORDER BY clause??? I ended up implementing it this way using an getXXXAttribute() method:
class Post extends Eloquent {
public function comments()
{
return $this->hasMany('Comment');
}
public function getCommentsAttribute()
{
$comments = $this->comments()->getQuery()->orderBy('created_at', 'desc')->get();
return $comments;
}
...
}
这篇关于雄辩地对数据进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!