网站首页php

Lavavel使用chunk批量更新数据时总漏掉一半

发布时间:2022-10-18 11:09:36编辑:阅读(1176)

    批量更新订单状态,使用计划任务定时执行,结果每次都有一半的数据被漏掉。
    代码如下所示:

    DB::table('order')
    ->where('published_at', '<', date('Y-m-d'))
    ->chunk(1000, function ($orders) {
            foreach ($orders as $order) {
                DB::table('order')->update(['published_at' => date('Y-m-d'));
            }
    });


    日志并无任何错误提示, 查看被漏掉的数据也并无任何异常。


    查看laravel的chunk描述

    If you are updating database records while chunking results, your chunk results could change in unexpected ways. 
    So, when updating records while chunking, it is always best to use the chunkById method instead. This method will 
    automatically paginate the results based on the record's primary key.


    大概是因为查询条件在chunk中被更新了,导致了不可预料的后果, 换成chunkById就可以了, 它可以根据记录ID来分页。

    DB::table('order')
    ->where('published_at', '<', date('Y-m-d'))
    ->chunkById(1000, function ($orders) {
            foreach ($orders as $order) {
                DB::table('order')->update(['published_at' => date('Y-m-d'));
            }
    });


    问题迎刃而解。

评论