Last active
October 1, 2017 11:30
-
-
Save josh7weaver/7d2b654d646ea0f27bb8 to your computer and use it in GitHub Desktop.
Insert or Update
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
$valueCollection = [ | |
['ABC - UNDERGRADUATE',"2015ABC",'COMM','COMM 2130','01','11620435234','20','0','2015/08/31 - 2015/12/17','0','1'], | |
['ABC - UNDERGRADUATE','2015ABC','COMM','COMM 21301','02','11620422234','20','0','2015/08/31 - 2015/12/17','0','1'] | |
]; | |
insertOrUpdate($valueCollection); |
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 insertOrUpdate(array $valueCollection) | |
{ | |
$columnNames = $this->getImportableAttributeNames(); | |
$columnNames[] = 'enabled'; | |
$columnNamesString = implode('`,`', $columnNames); | |
$table = $this->getTable(); | |
$values = $this->buildSqlValuesFrom( $valueCollection ); | |
$updates = $this->buildSqlUpdatesFrom( $columnNames ); | |
$params = array_flatten($valueCollection); | |
$query = "INSERT INTO $table (`$columnNamesString`) VALUES $values ON DUPLICATE KEY UPDATE $updates"; | |
// dd($query); | |
DB::statement($query, $params); | |
} | |
public function buildSqlUpdatesFrom(array $columnNames) | |
{ | |
$updates = ''; | |
foreach($columnNames as $column){ | |
$updates .= "`$column`=VALUES(`$column`),"; | |
} | |
return rtrim($updates, ','); | |
} | |
public function buildSqlValuesFrom(array $valueCollection) | |
{ | |
$values =''; | |
foreach ($valueCollection as $row) { | |
$values .= '(' . str_repeat("?,", count($row)) . "'1'"; | |
$values .= '),'; | |
} | |
return rtrim($values, ','); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment