I'm relatively new to Yii2 and so far I'm enjoying it very much.
I'm however finding an issue related with Database Inserts, more specifically MySQL.
The question is fairly simple: I'm inserting values into a table and I need to check for duplicates so my idea was to use an INSERT IGNORE or ON DUPLICATE KEY UPDATE.
This is the code I'm using for the insert:
'fb_id' => $app->id,
'page_id' => $page_id,
'name' => $app->name,
'app_id' => $app_id,
'app_name' => $app_name,
class MyQueryBuilder extends yii\db\mysql\QueryBuilder
public function batchInsert($table, $columns, $rows)
$sql = parent::batchInsert($table, $columns, $rows);
$sql .= 'ON DUPLICATE KEY UPDATE';
More than one year passed and I found this open question here. I see this has some traction, so it's good to add a proper answer.
In Yii2 the idea is to find the model, check if exists and then save. The framework will automatically update or insert, here's a snippet I got from here.
$model::YourModel::findOne(ID); // findOne() searches for the table key, you can use find()->where('=', 'column', 'name')->one(); to identify the model. if(!$model): $model = new YourModel; endif; $model->column_1 = 'text'; $model->column_2 = 123; // integer $model->save();