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?
I have two models 1- Transaction 2-TransactionItems
There are multiple rows(onclick add row) in transaction Items.
I want to store multiple rows of transactionitems in the database.
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.