U
U
ukoHka2017-10-18 15:44:36
Yii
ukoHka, 2017-10-18 15:44:36

How to set up a relation in Yii2 through a third table?

There are three models: Ts, Plans, Students
Is it possible to implement something like this?
Ts.php:

public function getPlans()
    {
        return $this->hasMany(Plans::className(), ['subject_id' => 'subject_id','teacher_id' => 'teacher_id', 'student.studyform_id' => 'studyform_id']);
    }

That is, the ts and plans tables have matching subject_id and teacher_id fields. But if you make a selection only for these fields, then for each ts.studyform_id all students.studyform_id are displayed, and only matching ones should be displayed.
There is a unique student for each plans, but there are too many students.studyform_id for ts.studyform_id
UPD:
In the ts table, the teacher_id, subject_id, studyform_id fields
In the plans table, the teacher_id, subject_id, student_id
fields In the students table, the id, studyform_id fields
For each ts.studyform_id, you need output plans with matching students.studyform_id

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Timofeev, 2017-10-18
@webinar

So there is an example in the documentation, linking through a table:
www.yiiframework.com/doc-2.0/guide-db-active-recor...

R
Roman Savitsky, 2017-10-18
@PRC

Hi, I did something similar, I stored post_id and tag_id in the linked table, here I
wrote in the model responsible for Posts

public function getTags()
    {
        return $this->hasMany(Tags::className(), ['id' => 'tag_id'])->viaTable('{{%statjiblogtags}}', ['post_id' => 'id']);
    }

statjiblogtags - a table in which the relationship between post_id and tag_id

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question