Answer the question
In order to leave comments, you need to log in
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');
[['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
]);
}
}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question