Laravel - 更新具有不同值的多个记录 [英] Laravel - update multiple records with different values
本文介绍了Laravel - 更新具有不同值的多个记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一张表,类似于此:
I have a table , similar to this:
| key | value |
|----------|-------|
| limit | 15 |
| viplimit | 25 |
| .. | |
我有一个数组:
Array
(
[0] => Array
(
[key] => limit
[value] => 10
)
[1] => Array
(
[key] => viplimit
[value] => 99
)
...
现在说我们有100行。更新对应于数组的表格的最佳方式是什么?
Now , saying we have 100 rows. What would be the best way to update the table corresponding to the array ?
每100行可以有一个查询选项,但这只是
There would be the option of a query for each 100 row, but that is just bad performance.
推荐答案
这应该可以工作:
$statement = "UPDATE mytable
SET key = CASE id
WHEN 1 THEN 'key'
WHEN 2 THEN 'another_key'
WHEN 3 THEN 'some_key'
END,
value = CASE id
WHEN 1 THEN 15
WHEN 2 THEN 25
WHEN 3 THEN 45
END
WHERE id IN (1, 2, 3)
");
DB::statement($statement);
只要想想如何创建正确的查询。如果是管理面板或者不经常运行的东西,我只是使用迭代来保持简单。
Just think how to create correct query. If it's admin panel or something that will be run not very often, I'd just use iteration to keep things simple.
这篇关于Laravel - 更新具有不同值的多个记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文