Yii inserts data in batches. Yii batch insert data now has the following data: $ userarray (0 array (id1, name Zhang San), 0 array (id2, name Li Si ),); now, if you want to batch insert these two pieces of data into the data table yii, batch insert the data.
The following data is available:
$ User = array (0 => array ('id' => 1, 'name' => 'Zhang San'), 0 => array ('id' => 2, 'name' => 'Lily '),);
Now, if you want to batch insert these two pieces of data into a data table, you generally want to use foreach and then call the insert or save method to insert the data. However, in the foreach loop operation, insert inserts only the first data, while save inserts only the second data. Why? Explanation:
Insert a row to the ActiveRecord-based attribute table. If the table's primary key is automatically incremental and is null before insertion, fill in the actual value after insertion. Note: This method is not executed for verification. You can call validate for verification. After the record is successfully inserted into the database, its isNewRecord attribute is set to false, and its scenario attribute is set to update.
In this case, how can we implement batch data insertion in addition to transactions? The following two methods are summarized:
Method 1
$model=new User();foreach($data as $attributes){ $_model=clone $model; $_model->setAttributes($attributes); $_model->save();}
Method 2
$model=new User();foreach($data as $attributes){ $model->isNewRecord=true; $model->setAttributes($attributes); $model->save()&&$model->id=0;}
Articles you may be interested in
- Module development and analysis of Yii framework
- Yii Framework Yiiapp ()
- Yii database addition, modification, and deletion operations summary
- How to configure the default controller and action in the yii Framework
- Summary of using database transactions in Yii
- Yii controller action parameter binding
- Yii database query operation summary
- Yii Framework cache Knowledge Summary
Struct now has the following data: $ user = array (0 = array ('id' = 1, 'name' = 'Zhang San'), 0 = array ('id' = 2, 'name' = 'Lily'),); now if you want to batch insert the two data into the data table...