how to add the missing record to the parent model easily



The ERD:

The child tabel: CONSTRAINT city_ibfk_1 FOREIGN KEY (country) REFERENCES country (country) ON UPDATE CASCADE

parent table country:



child table city

country   city

USA       New York

Using ActiveForm for the model of the child table:

<?= $form->field($model,‘country’)->textInput()?> <-- input here: France

<?= $form->field($model, ‘city’)->textInput()?> <-- input here: Paris

the validate failed.

Is there a easy way to add the France to the parent model at first automaticly with a option like this:

<?= $form->field($model,‘country’)->textInput([‘addToParentModel’ => true])?>


AFAIK, simple "No" is the answer.

I would not try to do it, but it could be possible to create a method in City model that ensures the parent Country’s existence before inserting/updating a record, probably in “beforeSave” method.

But I’d rather use a listbox or dropdown for the ‘country’ field in the form for the city.

One more thing. Why do you want to avoid a standard way that uses integers for the keys?

Thanks for the anwser.

I do make a dropdown form the country, but when a country model(or other model what ever) missed a record, I want the user contribute to extend the database with his enters; or in other situations, the users should make the whole new database by enter the new records that not exist.

The ERD here without keys was for simplicity.

I do add the surrogate Id key, although it’s only a option for me. I don’t put the keys in practice often.

Thanks again.