Laravel 4: how to “order by” using Eloquent ORM [duplicate]

时光怂恿深爱的人放手 提交于 2019-12-28 02:23:48

问题


Simple question - how do I order by 'id' descending in Laravel 4.

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?


回答1:


If you are using post as a model (without dependency injection), you can also do:

$posts = Post::orderBy('id', 'DESC')->get();



回答2:


If you are using the Eloquent ORM you should consider using scopes. This would keep your logic in the model where it belongs.

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();

More info: http://laravel.com/docs/eloquent#query-scopes




回答3:


This is how I would go about it.

$posts = $this->post->orderBy('id', 'DESC')->get();


来源:https://stackoverflow.com/questions/17553181/laravel-4-how-to-order-by-using-eloquent-orm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!