I'm wondering how you go about doing a bulk database INSERT
in Yii2
?
For example a normal INSERT
I would like so:
$sql = $this->db("INSERT INTO some_table(id,my_value) VALUES(:id,:my_value)");
$sql->bindValues([':id' => $id, ':my_value' => $my_value]);
$sql->execute();
Now what if I wanted to create a bulk INSERT
?
Without binding values you could it something like:
foreach ($foo as $bar) {
$data_sql .= '(' . $id . ',' "'" . $bar . "'),"
}
$data_sql = rtrim($data_sql, ',');
$sql = $this->db("INSERT INTO some_table(id,my_value) VALUES" . $data_sql);
$sql->execute();
But how can you achieve this if you still want to bind the values?
Edit: This question is not the same as the linked one as I am not using ActiveRecord
.
Edit 2:
Ideally it would be good if there was a solution that offered some flexibility, such as being able to write most of your own syntax, as one of the answers posted below:
Yii::$app->db->createCommand()->batchInsert('tableName', ['id', 'title', 'created_at'], [
[1, 'title1', '2015-04-10'],
[2, 'title2', '2015-04-11'],
[3, 'title3', '2015-04-12'],
])->execute();
...doesn't offer that. For this particular situation I need to use the IGNORE
statement, which the above solution doesn't offer.
There is a special batchInsert method for that:
Yii::$app->db->createCommand()->batchInsert('tableName', ['id', 'title', 'created_at'], [
[1, 'title1', '2015-04-10'],
[2, 'title2', '2015-04-11'],
[3, 'title3', '2015-04-12'],
])->execute();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With