我想对客户表做一些事情,并且有很多记录,所以我将使用块功能来执行每100条记录。我还想添加一个进度条来显示进度。
但我写的代码不起作用。 错误发生在“$ bar”变量。
$count = DB::table('customers')->count();
$bar = $this->output->createProgressBar($count);
DB::table('customers')->chunk(100, function ($customers,$bar) {
foreach($customers as $customer) {
//do something with customer
$bar->advance();
}
$bar->finish();
}
答案 0 :(得分:1)
这是正确的方法:
->chunk(100, function ($users) use ($bar){}
答案 1 :(得分:1)
以前的答案是 50% 正确
DB::table('customers')->chunk 每 100 行运行一次,因此您必须添加 $bar->finish();退出回调
$count = DB::table('customers')->count();
$bar = $this->output->createProgressBar($count);
DB::table('customers')->chunk(100, function ($customers,$bar) use($bar) {
foreach($customers as $customer) {
//do something with customer
$bar->advance();
}
}
$bar->finish();