Laravel Eloquent: Ordering results of all()

后端 未结 10 1537
野的像风
野的像风 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.

提交回复
热议问题