Home >Backend Development >PHP Tutorial >Yii batch insert data_PHP tutorial

Yii batch insert data_PHP tutorial

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-07-13 09:49:341215browse

yii batch insert data

Now there is the following data:

$user=array(
	0=>array('id'=>1,'name'=>'张三'),
	0=>array('id'=>2,'name'=>'李四'),
);

Now if you need to insert these two pieces of data into the data table in batches, generally everyone will think of using foreach, and then calling the insert or save method to insert the data. But the actual operation is in the foreach loop operation. Insert will only insert the first piece of data, but save will only insert the second piece of data. Why is this? The explanation is as follows:

Insert a row into the attribute table based on this ActiveRecord. If the table's primary key is auto-incremented and null before insert, it will be populated with the actual value after insert. Note that validation does not perform this method. You can call validate to perform verification. After the record is successfully inserted into the database, its isNewRecord property will be set to false, and its scenario property will be set to update.

In this case, how can we implement batch insertion of data besides using transactions? After experiments, the following two methods have been summarized:

The first method

$model=new User();
foreach($data as $attributes){
     $_model=clone $model;
     $_model->setAttributes($attributes);
     $_model->save();
}

The second method

$model=new User();
foreach($data as $attributes){
      $model->isNewRecord=true;
      $model->setAttributes($attributes);
      $model->save()&&$model->id=0;
}

Articles you may be interested in

  • Yii framework module development analysis
  • Understanding of Yii framework Yiiapp()
  • yii database addition , modification, deletion related operations summary
  • How to configure the default controller and action in the yii framework
  • Summary of how to use database transactions in Yii
  • Yii controller action parameter binding processing
  • Yii database query operation summary
  • Yii framework cache knowledge summary

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1019141.htmlTechArticleyii batch insert data now has the following data: $user=array(0=array('id'=1, 'name'='Zhang San'),0=array('id'=2,'name'='李思'),); Now if you need to batch insert these two pieces of data into the data table...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn