注意这里使用的是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);

文档参考:

  1. https://www.yiiframework.com/doc/api/1.1/CDbCommandBuilder#createMultipleInsertCommand-detail
  2. https://www.yiiframework.com/doc/api/1.1/CDbCommand#getText-detail

标签: yii

添加新评论