Yii2 inserts and updates data instances in batches, and yii2 inserts data instances.

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.