Hello.

I can't figure it all out. How to create a linked model in Yii2.

The problem is that there are two models of ActiveRecord.

model1 contains fields [id, A, B] model2 contains fields [id, C, model1_id].

Those. model2 must enter id model1 in the [model1_id] field.

Is it correct to register in model2?

public function getCustomer() { return $this->hasOne(Model1::className(), ['model1_model_id' => 'id']); } 

I wrote this, but model1_id does not write to the database. What is the mistake, how to be properly done?

In the database tables do not link.

Thank you in advance. )

    1 answer 1

    We look into the documentation and see the following example:

     return $this->hasOne(Customer::className(), ['id' => 'customer_id']); 

    That is, you need to swap fields and omit _model_ :

     return $this->hasOne(Model1::className(), ['id' => 'model1_id']); 
    • So. It turns out we have created a connection. But it will not be saved in the database? - Anatoliy.CHA
    • What do you have in mind? - Egor Smolyakov
    • That when creating a new record, when we specify the ABC fields, will the model1_id field be filled automatically? There will be a new entry. id - 7 A - 10 B -11 // model1 id-2 C -14 model1_id - will the number 7 be set automatically? // model2 It seems to have tried to explain clearly. - Anatoliy.CHA
    • one
      Of course not. When creating an entry in Model2 you must explicitly indicate in the model1_id field the model1_id ID from Model1 . - Egor Smolyakov
    • Everything. Got it. Thank. ) - Anatoliy.CHA