简体   繁体   中英

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

$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.

$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. So solution applies to Laravel. If you are using other framework, you can check similar method for it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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