2019-02-05 00:56
浏览 761

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?

图片转代码服务由CSDN问答提供 功能建议

在Laravel Eloquent Model :: all()函数中,默认排序是什么 对于返回的查询? 我问这个是因为我很确定它是按主键升序的,当您通过

  php创建模型时,默认执行'id'  artisan make:model Model -m 


 返回$ users  = User :: all(); 


任何属性的结果似乎都没有特定的顺序。 我完全知道我可以通过id来命令它们

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

但就在几天前,他们正在自动订购。 什么给出了?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

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.

    解决 无用
    打赏 举报
  • drbz99867 2019-02-05 01:24

    With a great agreement with FrankerZ's answer, I would like to add, whenever you wonder what query laravel is structuring under the ORM, DB listener will be quickest option to use :

    \DB::listen(function($sql) {

    W.r.t. this question it would give select * from users when you do User::all().

    Note: Check listen function as per the laravel version you are using, the parameter count are different in older and newer versions.

    Reference : Documentation Link

    解决 无用
    打赏 举报