Created
July 15, 2015 17:46
-
-
Save chongkan/e9ef85d8d89985276dd0 to your computer and use it in GitHub Desktop.
Laravel BatchUpdate DB 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
//http://stackoverflow.com/questions/26133977/laravel-bulk-update | |
public function updateBatch($tableName = "", $multipleData = array()){ | |
if( $tableName && !empty($multipleData) ) { | |
// column or fields to update | |
//var_dump($multipleData); | |
$updateColumn = array_keys($multipleData[0]); | |
//var_dump($updateColumn); | |
$referenceColumn = $updateColumn[0]; //e.g id | |
unset($updateColumn[0]); | |
$whereIn = ""; | |
$q = "UPDATE ".$tableName." SET "; | |
foreach ( $updateColumn as $uColumn ) { | |
$q .= $uColumn." = CASE "; | |
foreach( $multipleData as $data ) { | |
$q .= "WHEN ".$referenceColumn." = '".$data[$referenceColumn]."' THEN '".$data[$uColumn]."' "; | |
} | |
$q .= "ELSE ".$uColumn." END, "; | |
} | |
foreach( $multipleData as $data ) { | |
$whereIn .= "'".$data[$referenceColumn]."', "; | |
} | |
$whereIn = rtrim($whereIn, ', '); | |
$q = rtrim($q, ", ")." WHERE ".$referenceColumn." IN (". rtrim($whereIn, ' ').")"; | |
// Update | |
//echo $q; | |
//die; | |
return \DB::update(\DB::raw($q)); | |
} else { | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment