Answer the question
In order to leave comments, you need to log in
How to add relational model when inserting model in yii2?
Such a problem.
It is necessary to make sure that when One is inserted into the database, Two is also added. And the one received from Two->id has been upgraded to One->two_id.
It is impossible to take out the code outside the class!
/**
* @property int $id
* @property string $field
* @property int $two_id
*
* @property Two $two
*/
class One
{
// необходимо добавить $this->two_id. но добавить изнутри
// $Two = new Two();
// $Two->fied = $this->field;
// $Two->insert();
// $this->two_id = $Two->id;
}
/**
* @property int $id
* @property string $field
*/
class Two
{
}
$One = new One();
$One->field = 'blablabla';
$One->insert();
Answer the question
In order to leave comments, you need to log in
You are now moving in the wrong direction, why do you need to create and bind objects inside the model? this is a direct path to bad code. In fact, this is all a piece of business logic. And the business logic, as you know, should not be stored in ActiveRecord (I understand that you are using it), it should be stored in a separate class.
PS You can link these two records using link()
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question