Skip to content

Instantly share code, notes, and snippets.

@rakibdevs
Created February 1, 2021 12:15
Show Gist options
  • Save rakibdevs/d0a06b97b3e9f51bbdb7a5fb3f5facb2 to your computer and use it in GitHub Desktop.
Save rakibdevs/d0a06b97b3e9f51bbdb7a5fb3f5facb2 to your computer and use it in GitHub Desktop.
Build query for multiple row update with a single query
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