Skip to main content

批量插入数据

第一种情况:

全字段插入,就是这个数组中每条数据里面的键都和数据库里面字段名一致,且每个字段都有.

use yii\helpers\ArrayHelper;

$rows = [];
foreach ($models as $model) {
  if ($model->validate()) {
    $rows[] = $model->attributes;
  }
}
$rows = ArrayHelper::getColumn($models, 'attributes');
$postModel = new Post;
Yii::$app->db->createCommand()->batchInsert(Post::tableName(), $postModel->attributes(), $rows)->execute();


第二种情况,非全字段

$rows[] = [
  'title' => $model->title,
  'content' => $model->content,
];
Yii::$app->db->createCommand()->batchInsert(Post::tableName(), ['title', 'content'], $rows)->execute();