laravel 5.2 - Model::all() order by

倾然丶 夕夏残阳落幕 提交于 2020-06-09 16:47:29

问题


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

$posts = Post::all();

However I want this is reverse chronological order.

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


回答1:


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

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




回答2:


You can now use sortBy or sortByDesc:

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



回答3:


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 .



来源:https://stackoverflow.com/questions/35250080/laravel-5-2-modelall-order-by

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