How to do a bulk database insert in 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 中进行批量数据库插入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 Yii2 中进行批量数据库插入?
基础教程推荐
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
- 从字符串 TSQL 中获取数字 2021-01-01
- 带有WHERE子句的LAG()函数 2022-01-01
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
- 带更新的 sqlite CTE 2022-01-01
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
- MySQL 5.7参照时间戳生成日期列 2022-01-01
