Ooops, sorry.. this answer for yii2
If you dont use yii model, this function generates mysql syntax insert on duplicates key update
static function insertDuplicate($table, $columns, $duplicates, $values="",$ignores=false){
$params=array();
$names=array();
$tipe="VALUES";
$ignore=($ignores===true)?"IGNORE":"";
$placeholders=array();
if(is_array($columns)){
if(!isset($columns[0])){
foreach($columns as $name=>$value)
{
$names[]=$name;
if($value instanceof CDbExpression)
{
$placeholders[] = $value->expression;
foreach($value->params as $n => $v)
$params[$n] = $v;
}
else
{
$placeholders[] = ':' . $name;
$params[':' . $name] = $value;
}
}
}else{
$names=$columns;
}
$myColumn=implode(', ',$names);
if($values!=""){
$myValue=$values;
}else{
$myValue='('.implode(', ', $placeholders).')';
}
}else{
$myColumn=$columns;
$myValue=$values;
}
if($values!=""){
if(substr(strtoupper($values),0,6)=="SELECT"){
$tipe="";
}
}
$d = array();
if(is_array($duplicates)){
if(!isset($duplicates[0])){
foreach($duplicates as $duplicate=>$act)
{
if($act=="increase"){
$dup=$table.".".$duplicate . ' = '.$table.".".$duplicate.' + VALUES('.$duplicate.')';
}elseif($act=="decrease"){
$dup=$table.".".$duplicate . ' = '.$table.".".$duplicate.' - VALUES('.$duplicate.')';
}else{
$dup=$table.".".$duplicate . ' = VALUES('.$duplicate.')';
}
$d[] = $dup;
}
}else{
foreach($duplicates as $duplicate){
$dup=$duplicate . ' = VALUES('.$duplicate.')';
$d[] = $dup;
}
}
$myDuplicate= implode(', ', $d);
}else{
$myDuplicate=$duplicates;
}
$sql='INSERT '.$ignore.' INTO ' . $table
. ' (' . $myColumn . ') '.$tipe.' '
. $myValue . ' ON DUPLICATE KEY UPDATE ' .$myDuplicate;
return Yii::$app->db->createCommand($sql)->bindValues($params)->execute();
}
Place that function into someclass, and dont forget use
use yii\db\Command;
in that class
That function can insert on key update, update increment, update decrement, update multi from a value, and update from select
Usage :
//to update available=1 and price into 100
someclass::insertDuplicate(
'ck_space_calendar_cache',
['sapce_id'=>1,'day'=>'2022-09-01','available'=>1,'price'=>100],
['available','price']
);
//to update price increase by 100, (if price is decrease then change it to decrease)
someclass::insertDuplicate(
'ck_space_calendar_cache',
['sapce_id'=>1,'day'=>'2022-09-01','price'=>100],
['price'=>'increase']
);
//to update mass with a value
someclass::insertDuplicate(
'ck_space_calendar_cache',
['sapce_id','day','price'],
['price'],
'(1,'2022-09-01',100),(2,'2022-09-01',300),(3,'2022-09-01',100)'
);
//to update mass with select from another table
someclass::insertDuplicate(
'ck_space_calendar_cache',
['sapce_id','day','price'],
['price'],
'SELECT otherid as sapce_id, otherday as day, otherprice as price from other WHERE otherprice>100'
);