N
N
NetyNicka2015-07-19 01:23:26
MySQL
NetyNicka, 2015-07-19 01:23:26

How to make friends between forignKey and record creation in yii2?

Good day comrades! There is a table of cars (car[car_id,....,car_options_id]), there is a table of options for each car (car_options[ car_options_id
,....]).

$this->addForeignKey('FK_car_options', 'car', 'car_options_id', 'car_options', 'car_options_id', 'RESTRICT', 'RESTRICT');

The model contains the rule Therefore, when creating a machine, you must specify an already existing option id, which temporarily grew into:
[['car_user_id', 'car_options_id'], 'required'],
public function actionCreate()
    {
        $carModel = new Car();
        $carOptionsModel = new CarOptions();
        //ставится временный id 
        $carOptionsModel->car_options_id = 1;
        if (
            $carModel->load(Yii::$app->request->post()) && $carOptionsModel->load(Yii::$app->request->post())
        ) {
            if ($carModel->validate() && $carOptionsModel->validate()) {
                //Обнуляется при сохранении
                $carOptionsModel->car_options_id = null;
                $carOptionsModel->save();
                $carModel->car_options_id = $carOptionsModel->car_options_id;
                $carModel->save();
            }
            return $this->redirect(['view', 'id' => $carModel->car_id]);
        } else {
            return $this->render('create', [
                'model' => $carModel,
                'carOptions' => $carOptionsModel
            ]);
        }
    }

But something tells me that this is not the right solution, and there should be a more correct option. What is the right thing to do in this situation?

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
I
Igor Belikov, 2015-07-19
@NetyNicka

If I understand your table structure correctly, then you seem to have made a mistake in the design of the database.
In theory, you should have something like this:
With such a constructor, the default value will not need to be specified.
And then you install the relays and you will get a list of options like this:$car->options

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question