Implementation idea:
Inserting data in batches is to first integrate the data into an array, and then insert the array directly into the database, thereby achieving one Insert multiple pieces of data.
There are two situations
The first situation:
Full field insertion, that is, the key in each piece of data in this array is consistent with the field name in the database, and Every field has it.
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();
The second case:
Non-full fields
$rows[] = [ 'title' => $model->title, 'content' => $model->content, ]; Yii::$app->db->createCommand()->batchInsert(Post::tableName(), ['title', 'content'], $rows)->execute();
Related recommendations: yii
The above is the detailed content of How to add data to the database in batches in yii2. For more information, please follow other related articles on the PHP Chinese website!