Jos*_*osh 172 php laravel eloquent laravel-4
简单的问题 - 如何通过Laravel 4中的'id'降序排序.
我的控制器的相关部分如下所示:
$posts = $this->post->all()
Run Code Online (Sandbox Code Playgroud)
据我了解你使用这一行:
->orderBy('id', 'DESC');
Run Code Online (Sandbox Code Playgroud)
但是这与我上面的代码有什么关系呢?
Chr*_*s G 310
如果您使用post作为模型(没有依赖注入),您还可以:
$posts = Post::orderBy('id', 'DESC')->get();
Run Code Online (Sandbox Code Playgroud)
Rel*_*rus 54
如果您使用的是Eloquent ORM,则应考虑使用范围.这将使您的逻辑保持在它所属的模型中.
所以,在模型中你会有:
public function scopeIdDescending($query)
{
return $query->orderBy('id','DESC');
}
Run Code Online (Sandbox Code Playgroud)
在模型之外你会有:
$posts = Post::idDescending()->get();
Run Code Online (Sandbox Code Playgroud)
更多信息:http://laravel.com/docs/eloquent#query-scopes
小智 27
我就是这样做的.
$posts = $this->post->orderBy('id', 'DESC')->get();
Run Code Online (Sandbox Code Playgroud)