This operation of batch adding is often used in actual development. Today, I will take the time to sort out some information about batch adding in yii2. If you are interested, please take a look at this question.
In the last article, I introduced to you the Brief Analysis of Yii2 Gridview Implementation of Batch Deletion Tutorial. Of course, the focus is on how to operate gridview. Today we will talk about how to batch add data in Yii2 ?
Some students shouted that this is not simple. I made a foreach loop and directly inserted the data into the database in each loop. It was simple and crude! Damn it, brother, if you were in the same company as me, I think the chance of seeing you the next day would be slim!
Not much to say. If you say too much, you will scold me. Let’s get down to business. Let’s first look at a table structure that is simple enough for elementary school students to recognize.
//test id name
We are now going to batch insert 10 pieces of data into this data table in yii2
The way we want is definitely as follows, how simple and direct a SQL statement is to solve the problem
insert into test (name) values ('zhangsan'), ('lisi');
The analysis is all done, okay, let’s take a look at the specific implementation
//假如 $names = ['zhangsan', 'lisi']; $data = []; foreach ($names $k => $v) { $data[] = [$v]; } Yii::$app->db->createCommand()->batchInsert('test', ['name'], $data)->execute();
I believe many people are interested in whether AR can achieve batch insertion. The reason is simply that it is safer and more convenient to operate. But there seems to be no official manual, no, no. . . My heart is broken, there is none, at least I haven't found it. If you find it, please click on the original text to find me and contact me. I also need a way.
Unfortunately, I found an operation method related to AR. Let’s share it for reference and see what’s going on
Suppose there is an array $models of Post class, you can operate like this
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();
Although it’s back to batchInsert, it doesn’t matter. Everything that needs to be verified has been verified. There is no need to worry about security.
The above is the knowledge about how to batch add data in Yii2 introduced by the editor. I hope it will be helpful to everyone!