I have two models, Users and Students. I want to insert data into these tables simultaneously. First, I save data into Students model and then into Users models. 
Now, if data doesn't successfully get inserted into Users model there is already an entry into Students table. What I want is data entries into both model only if data can be successfully saved 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 users model and not return true when i call $userModel->save() . here, $userModel->save() return true and inserts data to the table.
Is there any other option to do this without any complication ?
You should use transactions to ensure both models are saved correctly. Example:
$transaction = Yii::$app->db->beginTransaction();
try  {
    if ($model->save() && $userModel->save()) {
        $transaction->commit();
    } else {
        $transaction->rollBack();
    }
} catch (Exception $e) {
    $transaction->rollBack();
}
                        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