Answer the question
In order to leave comments, you need to log in
How to deal with many-to-many yii2?
Hello.
I can't understand the logic of many-to-many relationships in yii2.
I have 3 tables:
public function getOrgans(){
return $this->hasMany(ProblemsOrgan::className(), ['ID' => 'organ_id'])
->viaTable('problems_has_organ', ['organ_id' => 'ID']);
}
Answer the question
In order to leave comments, you need to log in
Did it like this:
public function getOrgans(){
return $this->hasMany(ProblemsOrgan::className(), ['ID' => 'organ_id'])
->viaTable('problems_has_organ',['problem_id'=>'ID']);
}
Make three models:
In Problems: $this->hasMany(ProblemsHasOrgan::className(), ['organ_id' => 'ID'])
In ProblemsHasOrgan: $this->hasOne(ProblemsOrgan::className(), ['ID ' => 'problem_id'])
And that's it!
$problems = Problems->find()->with('ProblemsHasOrgan')->all();
foreach($problems->getProblemsHasOrgan->all() as $one)
{
echo $one->problemOrgan->name;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question