如何在 Yii2 中进行批量数据库插入?

How to do a bulk database insert in Yii2?(如何在 Yii2 中进行批量数据库插入?)
本文介绍了如何在 Yii2 中进行批量数据库插入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道你是如何在 Yii2 中进行批量数据库 INSERT 的?

I'm wondering how you go about doing a bulk database INSERT in Yii2?

例如一个普通的 INSERT 我想要这样:

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();

现在如果我想创建一个批量INSERT怎么办?

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?

这个问题与链接的问题不同,因为我没有使用 ActiveRecord.

This question is not the same as the linked one as I am not using ActiveRecord.

编辑 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();

...不提供.对于这种特殊情况,我需要使用 IGNORE 语句,上面的解决方案没有提供.

...doesn't offer that. For this particular situation I need to use the IGNORE statement, which the above solution doesn't offer.

推荐答案

有一个特殊的 batchInsert 方法:

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();

这篇关于如何在 Yii2 中进行批量数据库插入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)
SQL/MySQL: split a quantity value into multiple rows by date(SQL/MySQL:按日期将数量值拆分为多行)