M
M
McMike2016-11-02 09:57:53
Yii
McMike, 2016-11-02 09:57:53

How to write database relationships in Yii2?

I can not understand how writing to the database through models in Yii works.
There is a model corresponding to a certain table X1, the $X1model object is filled in and $X1model->save() is done. Somehow
the database is being written, ok.
Now the crux of the matter. There is another table X2, it should have records of the X connection with another table, a one-to-many relationship. How is this generally done in Yii2?
We need to record X1, then take the id of this new record, create $X2model, fill it in and do $X2model->save()?
Or is it possible to somehow fill $X1model with additional data and after $X1model->save() the links will also appear?
PS: didn't work with yii before

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Maxim Fedorov, 2016-11-02
@qonand

To save related data, use the link()
method. If you want to load everything into one model, use this https://github.com/voskobovich/yii2-many-to-many-b...

M
McMike, 2016-11-02
@McMike

It turned out that after save () the model has a primaryKey, then I work with another model using this key

M
Maxim Timofeev, 2016-11-03
@webinar

All your logic for working with related data should be in the afterSave method of the model. The id is already there.
If the link is 1 use link(), if there is a set of models that is Model::loadMultiple() and save them in a loop, in the same afterSave

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question