Mahmut Aydın
Mahmut Aydın

Reputation: 869

How to get auto increment id after save in Yii2

Im trying to get auto increment id after save in Yii2.I tried to the following code block but its not working.

public function actionAddgroup()
{
    $model = new Groups();
    $model->groupName=Yii::$app->request->post('groupName');

    $model->save();  // a new row is inserted into user table
    return $model->id;
}

Upvotes: 4

Views: 7692

Answers (2)

matt
matt

Reputation: 377

Where you are trying to return the $model->id immediately after creating a new Groups instance, the $model variable may still only have the data you put into it.

To get data added at the database level, you may need to call $model->refresh() in order for it to refresh the data in your local $model variable with the current data from the database.

In other words, try this:

public function actionAddgroup()
{
    $model = new Groups();
    $model->groupName=Yii::$app->request->post('groupName');

    $model->save();
    $model->refresh();
    return $model->id;
}

Upvotes: 3

Mahmut Aydın
Mahmut Aydın

Reputation: 869

public function actionAddgroup()
{
    $model = new Groups();
    $model->groupName=Yii::$app->request->post('groupName');

    $model->save();  // a new row is inserted into user table
    return $model->getPrimaryKey();
}

Upvotes: 1

Related Questions