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;
}
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;
}
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With