laravel 5.2 - Model::all() 排序方式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35250080/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 17:15:38  来源:igfitidea点击:

laravel 5.2 - Model::all() order by

laraveleloquent

提问by datavoredan

I get the full collection of a Model with the following:

我得到了一个完整的模型集合,如下所示:

$posts = Post::all();

$posts = Post::all();

However I want this is reverse chronological order.

但是我希望这是反向时间顺序。

What is the best way to get this collection in the desired order?

以所需顺序获取此集合的最佳方法是什么?

回答by Jilson Thomas

$posts = Post::orderBy('created_at', 'desc')->get();

You can use the orderBy method. Replace the column name with the one you want.

您可以使用 orderBy 方法。用您想要的名称替换列名称。

回答by Nicolas Perraut

You can now use sortByor sortByDesc:

您现在可以使用sortBysortByDesc

$posts = Post::all()->sortBy('created_at');

回答by conrad10781

As many may be moving to newer versions of Laravel, you can use ::latest() starting in 5.3 - https://laravel.com/docs/5.5/queries#ordering-grouping-limit-and-offset.

由于许多人可能会转向更新版本的 Laravel,您可以从 5.3 开始使用 ::latest() - https://laravel.com/docs/5.5/queries#ordering-grouping-limit-and-offset