Laravel Eloquent: Ordering results of all()

后端 未结 10 1500
野的像风
野的像风 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条回答
  • 2020-12-07 10:40

    DO THIS:

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

    Why? Because it's fast! The ordering is done in the database.

    DON'T DO THIS:

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

    Why? Because it's slow. First, the the rows are loaded from the database, then loaded into Laravel's Collection class, and finally, ordered in memory.

    0 讨论(0)
  • 2020-12-07 10:42

    While you need result for date as desc

    $results = Project::latest('created_at')->get();
    
    0 讨论(0)
  • 2020-12-07 10:45

    You instruction require call to get, because is it bring the records and orderBy the catalog

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

    Example:

    $results = Result::where ('id', '>=', '20')
    ->orderBy('id', 'desc')
    ->get();
    

    In the example the data is filtered by "where" and bring records greater than 20 and orderBy catalog by order from high to low.

    0 讨论(0)
  • 2020-12-07 10:47

    You can actually do this within the query.

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

    This will return all results with the proper order.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-07 10:55

    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

    0 讨论(0)
提交回复
热议问题