Yii2.0 批量插入数据

循环插入:

第一种方法:

$model=new User();
foreach($data as $attributes){
     $_model=clone $model;
     $_model->setAttributes($attributes);
     $_model->save();
}

第二种方法

$model=new User();
foreach($data as $attributes){
      $model->isNewRecord=true;
      $model->setAttributes($attributes);
      $model->save()&&$model->id=0;
}

Yii2.0批量插入:

Yii::$app->db->createCommand()->batchInsert(UserModel::tableName(), ['user_id','username'], [
    ['1','test1'],
    ['2','test2'],
    ['3','test3'],  
])->execute();

一个字段时

//假如 $names = ['zhangsan', 'lisi'];
$data = [];
foreach ($names $k => $v) {
    $data[] = [$v];
}
Yii::$app->db->createCommand()->batchInsert('test', ['name'], $data)->execute();

查看执行sql

/UserModel
$query = UserModel::find()->where(['status'=>1]);
echo $query->createCommand()->getRawSql();

你可能感兴趣的:(Yii2.0 批量插入数据)