Laravel Eloquent: Ordering results of all()

拈花ヽ惹草 提交于 2019-12-17 17:25:21

问题


I'm stuck on a simple task. I just need to order results coming from this call

$results = Project::all();

Where Project is a model. I've tried this

$results = Project::all()->orderBy("name");

But it didn't work. Which is the better way to obtain all data from a table and get them ordered?


回答1:


You can actually do this within the query.

$results = Project::orderBy('name')->get();

This will return all results with the proper order.




回答2:


You could still use sortBy (at the collection level) instead of orderBy (at the query level) if you still want to use all() since it returns a collection of objects.

Ascending Order

$results = Project::all()->sortBy("name");

Descending Order

$results = Project::all()->sortByDesc("name");

Check out the documentation about Collections for more details.

https://laravel.com/docs/5.1/collections




回答3:


In addition, just to buttress the former answers, it could be sorted as well either in descending desc or ascending asc orders by adding either as the second parameter.

$results = Project::orderBy('created_at', 'desc')->get();



回答4:


2017 update


Laravel 5.4 added orderByDesc() methods to query builder:

$results = Project::orderByDesc('name')->get();



回答5:


While you need result for date as desc

$results = Project::latest('created_at')->get();



回答6:


DO THIS:

$results = Project::orderBy('name')->get();

DON'T DO THIS:

$results = Project::all()->sortBy('name');

WHY? Briefly, the first approach is faster than the second approach.




回答7:


Check out the sortBy method for Eloquent: http://laravel.com/docs/eloquent




回答8:


Note, you can do:

$results = Project::select('name')->orderBy('name')->get();

This generate a query like:

"SELECT name FROM proyect ORDER BY 'name' ASC"

In some apps when the DB is not optimized and the query is more complex, and you need prevent generate a ORDER BY in the finish SQL, you can do:

$result = Project::select('name')->get();
$result = $result->sortBy('name');
$result = $result->values()->all();

Now is php who order the result.



来源:https://stackoverflow.com/questions/17429427/laravel-eloquent-ordering-results-of-all

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