Batch adding is an operation. If it is used in actual development, it must be used. Otherwise, why do so many people still have nothing to do with Baidu, Google, and that every day? It is a real need.
We have written before Regarding 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 yelled, 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 are in the same company as me, I think the probability of seeing you the next day is very low!
Not much to say, you are scolding me if I say too much, let’s get down to business, first look at a table structure that is simple enough for elementary school students to know
<span>//</span><span>test </span><span>id name</span>
We are now going to batch insert this data table in yii2 10 pieces of data
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 has been completed, 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 They are all aimed at 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 don't pay attention to them. The source of the original article is clearly stated. The original author also hopes that readers can read the original article in case there are any problems and cannot update all articles to avoid misleading! ]
Continue reading
The above introduces the issues of batch adding in yii2, including the content of yii. I hope it will be helpful to friends who are interested in PHP tutorials.