Home > PHP Framework > YII > body text

How to add data to the database in batches in yii2

王林
Release: 2020-12-08 15:44:24
forward
3532 people have browsed it

How to add data to the database in batches in yii2

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();
Copy after login

The second case:

Non-full fields

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

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!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template