在使用一个命令行脚本给某个表加个辅助字段,使用laravel的模型里的chunk,结果代码里有部分数据没有处理被跳过去了。

 public function handle()
    {
        $start_time = microtime(true);
        TestModel::select(['id','created_time'])
            ->whereNull('create_date') //关键条件
            ->chunk(200,function ($notes){
            collect($notes)->each(function($item){
                if(empty($item['create_date']))
                {
                    TestModel::where('id',$item['id'])->update(['create_date'=>date('Y-m-d',$item['created_time'])]); //问题所在
                }
            });
        });
        $end_time = microtime(true);
        echo "Run over!take time (s):".($end_time - $start_time);
        exit;
    }

典型的思维陷阱,因为create_date的数据在变,使用chunk方法在处理第二页时实际处理的是第三页的数据(因为create_date在第一页时数据已经处理完成了,而再进行select * from test limit 100,200),因此在数据处理完成后已经实际的数据在已经位移到第limit 200, 200)从而跳过去了。

解决方式的话,1是直接用个while死循环查询,当没有数据事再break掉;2是不把whereNull('create_date')这个条件加进去。

标签: none

评论已关闭