Is it possible to insert multiple rows in one query with Yii's ActiveRecord? Or is this only possible via the lower-level DAO objects?
相关问题
- Views base64 encoded blob in HTML with PHP
- Laravel Option Select - Default Issue
- PHP Recursively File Folder Scan Sorted by Modific
- Can php detect if javascript is on or not?
- Using similar_text and strpos together
You can use
batchInsert()
method ofyii\db\Command
. See details here. When using it withActiveRecord
make sure validate all data before inserting.Assuming you have array of $models with class
Post
, it can be done like this:If models don't require validation you can short the code above using
ArrayHelper
for building$rows
array.Then simply execute batch insert:
P.S. The
$postModel
just used for pulling attirubute names list, you can also pull this from any existing $model in your $models array.If you don't need to insert all attributes you can specify it when filling
$rows
array:Don't forget to replace
$postModel->attributes
to['title', 'content']
.In case of larger amount of attributes you can use some array functions to specify exact attributes for inserting.