Reputation: 869
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
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
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