Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get auto increment id after save in Yii2

Tags:

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;
}
like image 473
Mahmut Aydın Avatar asked Oct 28 '25 22:10

Mahmut Aydın


2 Answers

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;
}
like image 181
matt Avatar answered Oct 30 '25 18:10

matt


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();
}
like image 38
Mahmut Aydın Avatar answered Oct 30 '25 16:10

Mahmut Aydın