Home >Backend Development >PHP Tutorial >Problems with batch adding in yii2, problems with batch adding in yii2_PHP tutorial
Batch adding is an operation. If it is used in actual development, it must be used. Otherwise, how can you still do it? There are so many people who have nothing to do with Baidu, Google, and that every day, right? They have real needs
We have written before about how to batch delete data through gridview in yii2. 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.
<span>//</span><span>test </span> <span>id name</span>
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
<span>//</span><span>假如 $names = ['zhangsan', 'lisi']; </span> <span>$data</span> =<span> []; </span><span>foreach</span> (<span>$names</span> <span>$k</span> => <span>$v</span><span>) { </span><span>$data</span>[] = [<span>$v</span><span>]; } Yii</span>::<span>$app</span>->db->createCommand()->batchInsert('test', ['name'], <span>$data</span>)->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
[Considering that most domestic websites currently collect articles very frequently, and some even do not indicate the source of the original article, the original author hopes that readers can check the original article to prevent any problems and not update all articles to avoid misleading! ]
Continue reading