Home >Backend Development >PHP Tutorial >Yii batch insert data_PHP tutorial
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; }