Yii2 inserts and updates data instances in batches, and yii2 inserts data instances.
When using yii2 to develop a project, you may encounter the following situations:
Send multiple data records to the backend. Some of the data already exists. You only need to modify the values of some of its fields. The other part of the data needs to be added to the backend.
This requires judgment on the added data, some of which execute update and the rest execute insert
The Code is as follows. For more information, see:
// Update the data in batches and insert the data to the array into the foreach ($ goods as $ k => $ v) {if (yourModel :: updateAllCounters (['goods _ num' => $ v], ['goods _ id' => $ k, 'user _ id' => $ id]) {continue; // skip this loop if it has been updated to the next time} $ data [] = ['user _ id' => $ id, 'Goods _ id' => $ k, 'goods _ num' => $ v, 'created _ time' => $ time,]} // execute the batch insert if (isset ($ data) {Yii ::$ app-> db-> createCommand ()-> batchInsert (yourModel: tableName (), ['user _ id', 'goods _ id', 'goods _ num', 'created _ time'], $ data)-> execute ();}
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.