How to Use yii to insert multiple data records at a time is very difficult. Today, I tried to look at the source code and thought of a way. If there is any error, please contact me in time to correct it in order to avoid misleading others, I hope you can refer to this blog for more information.
Look at the code with little nonsense:
$ Db = Yii: app ()-> db; $ transaction = $ db-> beginTransaction (); $ command = $ db-> createCommand (); try {$ _ files = array ('name' => 'abc', 'SIZE' => '000000'), array ('name' => 'abc2 ', 'SIZE' => '000000'), array ('name' => 'abc3', 'SIZE' => '000000'); if ($ _ files) {foreach ($ _ files as $ files) {$ command-> reset (); foreach ($ files as $ k => $ v) {$ columArray [$ k] = $ v;} $ command-> insert (FileConvert: model ()-> tableName (), $ columArray );}} $ transaction-> commit (); return true;} catch (Exception $ e) {$ transaction-> rollback (); // if the operation fails, return false for data rollback ;}
After the command is reset with reset () for each loop, insert does not drop excetue () for execution, because it will be automatically executed during commit, so that you can insert multiple pieces of data at a time without having to spell SQL.
However, this is a drawback. If you execute a lot of items at a time, the efficiency will be slow. After all, this is equivalent to executing multiple such SQL statements: insert into table values ('A', 'B ');
The SQL statement we manually spell is as follows: insert into table values ('A', 'B'), ('C', 'D'); this is relatively more efficient.
Therefore, if less data is written, you can use the above method.