gpt4 book ai didi

php - Eloquent chunk()遗漏了一半的结果

转载 作者:行者123 更新时间:2023-12-04 16:08:17 27 4
gpt4 key购买 nike

我对Laravel的ORM Eloquent chunk()方法有疑问。
它错过了一些结果。
这是一个测试查询:

$destinataires = Destinataire::where('statut', '<', 3)
->where('tokenized_at', '<', $date_active)
->chunk($this->chunk, function ($destinataires) {
foreach($destinataires as $destinataire) {
$this->i++;
}
}
echo $this->i;

它给出124838个结果。

但 :
$num_dest = Destinataire::where('statut', '<', 3)
->where('tokenized_at', '<', $date_active)
->count();
echo $num_dest;

给出249676,因此仅TWICE作为第一个代码示例。

我的脚本应该编辑数据库中所有匹配的记录。如果我多次启动它,则每次仅分发剩余记录的一半。

我尝试使用DB::table()而不是Model。
我尝试添加-> take(20000),但似乎未考虑在内。
我用-> toSql()回显了查询,并且eveything看起来还不错(当我添加-> take()参数时,就添加了LIMIT子句)。

有什么建议 ?

最佳答案

快速解答:使用chunkById()代替chunk()

可以在Laravel documentation中找到的说明:

When updating or deleting records inside the chunk callback, any changes to the primary key or foreign keys could affect the chunk query. This could potentially result in records not being included in the chunked results.



这是解决方案示例:
DB::table('users')->where('active', false)
->chunkById(100, function ($users) {
foreach ($users as $user) {
DB::table('users')
->where('id', $user->id)
->update(['active' => true]);
}
});

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()方法的回调函数。

这是有问题的代码:
Transaction::whereNull('processed')->chunk(100, function ($transactions) {
$transactions->each(function($transaction){
$transaction->process();
});
});

我使用了Laravel 5.4,并设法解决了用 cursor()方法替换 chunk()方法并相应地更改代码的问题:
foreach (Transaction::whereNull('processed')->cursor() as $transaction) {
$transaction->process();
}

即使答案不能解决问题本身,也可以提供有值(value)的解决方案。

关于php - Eloquent chunk()遗漏了一半的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32700537/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com