doucepei5298 2019-02-05 00:56
浏览 983
已采纳

Laravel Eloquent Model :: all()函数的默认排序是什么?

In the Laravel Eloquent Model::all() function, what is the default ordering for the returned query? I ask this because I'm pretty sure it's in ascending order by primary key which defaults do 'id' when you make the model through

php artisan make:model Model -m

However, when I call it like this:

return $users = User::all();

I get the following results in the browser:

Eloquent all() function results

The results seem to be in no particular order by any of the attributes. I am fully aware I can order them by id by doing

return $users = User::orderBy('id', 'asc')->get();

But just a few days ago they were being ordered automatically. What gives?

  • 写回答

2条回答 默认 最新

  • dqwh1119 2019-02-05 00:58
    关注

    The default sort order for laravel is simply nothing. It does not apply a default "ORDER BY" clause, which means that it follows PostgreSQL rules for unordered results. From some similar answers here and here:

    • Do not depend on order when ORDER BY is missing.

    • Always specify ORDER BY if you want a particular order -- in some situations the engine can eliminate the ORDER BY because of how it does some other step.

    • GROUP BY forces ORDER BY. (This is a violation of the standard. It can be avoided by using ORDER BY NULL.)

    SELECT * FROM tbl -- this will do a "table scan". If the table has never had any DELETEs/REPLACEs/UPDATEs, the records will happen to be in the insertion order, hence what you observed.

    If you had done the same statement with an InnoDB table, they would have been delivered in PRIMARY KEY order, not INSERT order. Again, this is an artifact of the underlying implementation, not something to depend on.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?