Laravel Eloquent Aggregates (Max) return 500 server error

时间:2016-04-04 18:28:41

标签: php mysql laravel-5

I am using this previously to get the MAX recordID from eloquent model. Unfortunately when the database table row more than 20k then it will return 500 internal server error.

I have checked laravel.log and also apache error log but couldn't get any clue..

After that I try to echo "XXX"; exit(); before each line of my code and found that the exit() stop run after this line.

$lastRecord_sync = \App\TableModel::all()->max('record_id');

Then I tried to change to below and it just working fine.

$lastRecord_sync = DB::table('tms_door_record_raw')->max('record_id');

May I know what is actually the issue here? Does the SQL different from Eloquent Model and DB Query builder?

1 个答案:

答案 0 :(得分:1)

此代码:

$lastRecord_sync = \App\TableModel::all()->max('record_id');

告诉laravel将表中的所有记录作为集合检索,然后获取该集合中的最大record_id(请参阅:Collections: max),大概是通过循环遍历整个集合,这可能非常如果你有很多记录,那就很慢。

第二个片段:

$lastRecord_sync = DB::table('tms_door_record_raw')->max('record_id');

告诉laravel意外执行此查询(请参阅:Query Builder: Aggregates):

SELECT MAX('record_id') FROM table;

MySQL在查找最大记录方面效率要高于PHP循环遍历集合中的每条记录并在那里找到最大record_id