Yii2 batch addition problem, yii2 batch addition Problem
Add this operation in batches. It must be used in actual development. Otherwise, you can see that there are still so many people who have nothing to do with Baidu and google every day, right, living Needs
We have previously written about how to delete data in batches through the gridview in yii2. Of course, the focus is on how to operate the gridview. Now let's talk about how to add data in batches in yii2?
This is not easy. I use foreach to insert data directly into the database in each loop, which is simple and rude! If you are in a company with me, I don't think it would be possible to see you the next day!
Let's not talk much about it. If you scold me too much, let's get into the question. Let's first look at a table structure that is simple to what pupils know.
//test id name
Now we want to insert 10 data records in batch for this data table in yii2.
The method we want must be the following: how straightforward an SQL statement is.
insert into test (name) values ('zhangsan'), ('lisi');
The analysis is complete. All right, let's take a look at the specific implementation.
// Assume $ names = ['hangsan', 'lisi']; $ data = []; foreach ($ names $ k => $ v) {$ data [] = [$ v];} Yii: $ app-> db-> createCommand ()-> batchInsert ('test', ['name'], $ data)-> execute ();
I believe that many people aim at whether AR can be inserted in batches. The reason is that it is safer and easier to operate. But the official Manual does not seem to exist. No, no... My heart is broken. I didn't find it. At least I didn't find it. If you find it, click the original text to find me and contact me. I also need a method for si.
Unfortunately, I found an operation method associated with AR. Let's share it and see how it works.
[Considering that most of the articles collected on Chinese websites are very frequent at present, the author does not specify the source of the original article. The original author prefers the readers to check the original article to avoid updating all the articles due to any problems and avoid misleading.]
Continue reading