E
E
evilelf2016-03-14 10:39:35
Yii
evilelf, 2016-03-14 10:39:35

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:

  • problems (organ)
  • problems_organ (ID)
  • problems_has_organ

You need to link problems to problems_organ, through problems_has_organ.
Here are the columns:
brR5Z9VSQMBkyA.jpg
Models:
  • ProblemsOrgan - all organs
  • Problems - all problems

I do it like this:
public function getOrgans(){
        return $this->hasMany(ProblemsOrgan::className(), ['ID' => 'organ_id'])
                ->viaTable('problems_has_organ', ['organ_id' => 'ID']);
    }

Only 1 organ is returned.
How to make a connection so that everything works fine?
If possible, explain the logic) everywhere only general explanations.
Thanks in advance.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
evilelf, 2016-03-14
@evilelf

Did it like this:

public function getOrgans(){
        return $this->hasMany(ProblemsOrgan::className(), ['ID' => 'organ_id'])
                ->viaTable('problems_has_organ',['problem_id'=>'ID']);
    }

Works. What other ways are there?

M
Maxim Timofeev, 2016-03-14
@webinar

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 question

Ask a Question

731 491 924 answers to any question