Laravel 4:如何使用雄辩的ORM [duplicate]来“排序”

时间:2022-10-15 23:26:30

This question already has an answer here:

这个问题已经有了答案:

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?

但是这和我上面的代码有什么关系呢?

3 个解决方案

#1


219  

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

如果您使用post作为模型(没有依赖注入),您也可以这样做:

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

#2


47  

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

如果您正在使用雄辩的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();

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

更多信息:http://laravel.com/docs/eloquent # query-scopes

#3


24  

This is how I would go about it.

这就是我要做的。

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

#1


219  

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

如果您使用post作为模型(没有依赖注入),您也可以这样做:

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

#2


47  

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

如果您正在使用雄辩的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();

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

更多信息:http://laravel.com/docs/eloquent # query-scopes

#3


24  

This is how I would go about it.

这就是我要做的。

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