Quentinb
Quentinb

Reputation: 510

Yii2 Attempt to read property "id" on int

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.

Upvotes: 0

Views: 566

Answers (1)

Michal Hynčica
Michal Hynčica

Reputation: 6144

Method yii\db\Command::execute() doesn't return model. It returns int representing the number of rows affected by executed query.

So, if you do

$user_model=$connection->createCommand()
    ->insert('tbl_user', [
        'name' => 'yii',
        'status' => 1,
    ])->execute();

Then the value in $user_model variable is most likely 1. And of course you can't do 1->id.

To get the ID of the new user you have to call yii\db\Connection::getLastInsertID().

For example like this:

$transaction = $connection->beginTransaction();
try {
    $connection->createCommand()
         ->insert('tbl_user', [
             'name' => 'yii',
             'status' => 1,
         ])->execute();
    $userId = $connection->getLastInsertID();
    $connection->createCommand()
        ->insert('tbl_user_roles', [
            'role' = "admin",
            'user_id'= $userId
        ])->execute();
    //...
    $transaction->commit();
} catch(Exception $e) {
    $transaction->rollback();
}

Upvotes: 0

Related Questions