php Laravel 4:如何使用 Eloquent ORM “排序”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17553181/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel 4: how to "order by" using Eloquent ORM
提问by Josh
Simple question - how do I order by 'id' descending in Laravel 4.
简单的问题 - 如何在 Laravel 4 中按“id”降序排序。
The relevant part of my controller looks like this:
我的控制器的相关部分如下所示:
$posts = $this->post->all()
As I understand you use this line:
据我了解,您使用这一行:
->orderBy('id', 'DESC');
But how does that fit in with my above code?
但这如何与我上面的代码相适应?
回答by Chris G
If you are using post as a model (without dependency injection), you can also do:
如果您使用 post 作为模型(没有依赖注入),您还可以执行以下操作:
$posts = Post::orderBy('id', 'DESC')->get();
回答by Relaxing In Cyprus
If you are using the Eloquent ORM you should consider using scopes. This would keep your logic in the model where it belongs.
如果您正在使用 Eloquent ORM,您应该考虑使用范围。这将使您的逻辑保持在它所属的模型中。
So, in the model you would have:
因此,在模型中,您将拥有:
public function scopeIdDescending($query)
{
return $query->orderBy('id','DESC');
}
And outside the model you would have:
在模型之外,您将拥有:
$posts = Post::idDescending()->get();
回答by Matthew Camp
This is how I would go about it.
这就是我要做的。
$posts = $this->post->orderBy('id', 'DESC')->get();