Laravel Eloquent: Ordering results of all()

后端 未结 10 1518
野的像风
野的像风 2020-12-07 10:09

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

$results = Project::all();

Where Project is

10条回答
  •  Happy的楠姐
    2020-12-07 10:54

    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.

提交回复
热议问题