I tried implementing Transactions using example below on Yii2 inside my Model class.
<php
$transaction = $connection->beginTransaction();
try {
$user_model=$connection->createCommand()
->insert('tbl_user', [
'name' => 'yii',
'status' => 1,
])->execute();
$connection->createCommand()
->insert('tbl_user_roles', [
'role' = "admin",
'user_id'= $user_model->id
])->execute();
//.....
$transaction->commit();
} catch(Exception $e) {
$transaction->rollback();
}
?>
But I keep getting error:
Attempt to read property "id" on int on this line:
'user_id'= $user_model->id
When I remove the second createCommand, the user insert works, so nothing wrong there.
Method
yii\db\Command::execute()doesn't return model. It returnsintrepresenting the number of rows affected by executed query.So, if you do
Then the value in
$user_modelvariable is most likely1. And of course you can't do1->id.To get the ID of the new user you have to call
yii\db\Connection::getLastInsertID().For example like this: