简体   繁体   English

将多行更新为其唯一ID,并在laravel中更改一个值

[英]Update multiple rows to their unique id with one value changed in laravel

I have below Array (50 elements in this array. so below mysql query fires 50 times.) to update in DB 我有下面的数组(这个数组中的50个元素。所以下面的mysql查询会触发50次。)来更新数据库

$array = [['id'=>1,'result'=>'21.25'],['id'=>2,'result'=>'13.03']]// ... up to 50 elements in this array. so below mysql query fires 50 times.

And I am doing like this. 而我这样做。

foreach ($array as $key => $value) {
    $postArray =  ['result' => $value['result']];
    DB::table('table')->where('id',$value['id'])->update($postArray);
}

Question : Is it possible to merge all in one query ? 问题:是否可以在一个查询中合并所有内容?

I tried like this but not working, 我试过这样但不行,

giving error `"errormsg":"Database error!! preg_replace(): Parameter mismatch, pattern is a string

while replacement is an array"` 而替换是一个数组“`

foreach ($array as $key => $value) {
    $postArray[] =  [
        'id' => $value['id'],
        'result' => $value['result']
    ];
}
DB::table('table')->update($postArray);

You can use whereIn() function to update multiple row with same data. 您可以使用whereIn()函数更新具有相同数据的多行。

$idArray = array(1, 2, 3);
$postArray =  ['result' => $value['result']];
DB::table('table')->whereIn('id',$idArray)->update($postArray);

Note: From code syntax, I have assumed you are using Laravel framework. 注意:从代码语法,我假设您使用的是Laravel框架。 So solution applies to Laravel. 所以解决方案适用于Laravel。 If you are using other framework, you can check similar method for it. 如果您正在使用其他框架,则可以检查类似的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM