Created
February 1, 2021 12:15
-
-
Save rakibdevs/d0a06b97b3e9f51bbdb7a5fb3f5facb2 to your computer and use it in GitHub Desktop.
Build query for multiple row update with a single query
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public function buildUpdateQuery($table, $update) | |
{ | |
$qr = "update ".$table." set "; | |
$cases = []; | |
$ids = []; | |
foreach ($update as $key => $val) { | |
$ids[] = $val['id']; | |
foreach ($val['data'] as $k => $v) { | |
$cases[$k][] = "when ".$val['id']." then '".$v."'"; | |
} | |
} | |
foreach ($cases as $k => $vl) { | |
if(collect($cases)->keys()->last() == $k){ | |
$qr .= $k.' = case id '.implode(" ",$vl).' end '; | |
}else{ | |
$qr .= $k.' = case id '.implode(" ",$vl).' end ,'; | |
} | |
} | |
$qr .= " where id in (".implode(', ',$ids).")"; | |
DB::statement($qr); | |
return 'success'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment