Skip to content

Instantly share code, notes, and snippets.

@josh7weaver
Last active October 1, 2017 11:30
Show Gist options
  • Save josh7weaver/7d2b654d646ea0f27bb8 to your computer and use it in GitHub Desktop.
Save josh7weaver/7d2b654d646ea0f27bb8 to your computer and use it in GitHub Desktop.
Insert or Update
$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);
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