Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do a bulk database insert in Yii2?

Tags:

mysql

yii

yii2

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.

like image 539
Brett Avatar asked Apr 11 '15 17:04

Brett


1 Answers

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();
like image 178
Pavel Bariev Avatar answered Oct 02 '22 04:10

Pavel Bariev