M
M
Michael2019-07-31 01:36:04
Yii
Michael, 2019-07-31 01:36:04

How to save linked models?

Hello everybody! There are two tables Accept and Address, both tables are related. When saving the form, there is such a need to save to the Address table in the accept_id id field from the Accept table received at the time of saving. In the controller, I probably also have some errors, so I will be grateful for the help, since for the first time I am doing the saving of related tables.

public function actionCreate()
{
        $model = new Accept();
        $address = new Address();
        $address->accept_id = $accept->id;

        if ($model->load(Yii::$app->request->post()) && $address->load(Yii::$app->request->post())){
            $address->accept_id = $model->id;
            if($model->validate() && $address->validate()){
                if($model->save() && $address->save()){
                     return $this->redirect(['view', 'id' => $model->id]);
                }
            }
            return $this->render('create', compact('model', 'address'));
        }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim, 2019-07-31
@Bally

link If that's enough.
But if you need a wider solution install a good extension: https://github.com/la-haute-societe/yii2-save-rela...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question