【发布时间】:2018-02-14 13:57:15
【问题描述】:
我正在使用 Laravel 开发一个数据库驱动的网站。现在我在更新数据库时遇到问题。我想运行批量更新。平时我是这样跑的。
$data = [
[
'col_1'=>$value1
],
[
'col_1'=>$value2
],
[
'col_1'=>$value3
],
[
'col_1'=>$value4
]
];
MyTableObject::update($data)->where('col_2'=>$col_2_val);
正如您在上面的代码中看到的,where 子句只检查所有要更新的行的一个条件。但我想要的是每行或查询都需要不同的 where 子句条件。要对每一行使用 foreach 并运行查询,这将非常耗时,因为我必须更新很多行。为了演示它,它将是这样的。
$data = [
[
'col_1'=>$value1,
'col_2'=>$where_value_1 // This is not the column to be updated. That is for where clause.
],
[
'col_1'=>$value2,
'col_2'=>$where_value_2 // This is not the column to be updated. That is for where clause.
],
[
'col_1'=>$value3,
'col_2'=>$where_value_3
],
[
'col_1'=>$value4,
'col_2'=>$where_value_4
]
];
MyTableObject::update($data)->where('where_col_name'=>'col_2');
我找到了this link,但答案并不清晰和完整。是否可以在 Laravel 中实现,我该怎么做?
【问题讨论】:
-
为什么不在阵列上运行 foreach?应该不会很费时间...
-
我必须更新数千条记录。所以我必须为每一行运行数千个查询。这很耗时。是的,我必须肯定使用 foreach,但我想知道如何在一个查询中更新?
-
试试 MyTableObject::where('where_col_name'=>'col_2')->update($data);
-
您的查询基本上是一组多个 where 子句,用于更改每个 where 条件的字段。所以,我认为它不能在单个查询中完成。您肯定需要考虑使用 for 循环,或者您的数据库模型可能不太正确。
-
那为什么不将它作为 cron 运行,或者在需要更新时将其推送到队列中并处理它
标签: php mysql laravel bulkupdate