yii 1.1 要使用 insert ignore into 语句批量写入数据的方法
注意这里使用的是yii 1.1版本
有时候我们要批量写入数据,同时还要去重复,如下的方法可能有用(数据库设置了唯一索引)
$this->db = new CDbConnection('mysql:host=dev.database.local;port=3306;dbname=xxx', 'xxx', 'xxx');
$data = [
['areaId'=>1, 'title'=>'text1'],
['areaId'=>2, 'title'=>'text2'],
['areaId'=>3, 'title'=>'text3'],
];
$builder = $this->db->schema->getCommandBuilder();
$command = $builder->createMultipleInsertCommand("{{ztags}}", $data);
$sql = $command->getText();
$sql = str_replace('INSERT INTO', 'INSERT IGNORE INTO', $sql);
$params = [];
foreach ($data as $i=>$d) {
foreach ($d as $k=>$v) {
$params[":{$k}_{$i}"] = $v;
}
}
$this->db->createCommand($sql)->execute($params);
文档参考:
- https://www.yiiframework.com/doc/api/1.1/CDbCommandBuilder#createMultipleInsertCommand-detail
- https://www.yiiframework.com/doc/api/1.1/CDbCommand#getText-detail
版权属于:Joyber
本文链接:https://blog.qqvbc.com/default/345.html
转载时须注明出处及本声明