I have two models: Usersand Students. I want to insert data into these tables at the same time. First, I save the data in the model Students, and then in the models Users.
Now, if the data is not successfully inserted into the model Users, there is already a record in the table Students. What I want is data records in both models, only if the data can be successfully stored in both.
Now my controller code looks something like this:
public function actionCreate()
{
$model = new Students();
$userModel = new Users();
if ($model->load(Yii::$app->request->post()) && $userModel->load(Yii::$app->request->post()) && $model->save() && $userModel->save())
{
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
'userModel' => $userModel,
]);
}
}
there is an error in the user model and does not return true when I call $userModel->save(). here $userModel->save()returns true and inserts data into the table.
Is there any other way to do this without any complications?