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 中进行批量数据库插入?
基础教程推荐
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- 无法解决整理冲突 2021-01-01
- 在 SQL 中连接多个表 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- 是否可以执行按位分组功能? 2021-01-01
