mozaika
(Ilovebreslev)
1
Hello
I want to get data based on there db tables
There is ‘student’ table
'course' table
and ‘student_in_course’ table (which holds foreign keys from both tables and represents all
courses that a student is registered to)
I would like to get all ‘course’.‘name’
based on ‘student_in_course’.‘course_id’ for a specific ‘student_in_course’.‘student_id’
What’s the best way of doing it with ActiveRecord (or other reccomended way)?
Thanks in advance
alirz23
(Alirz23)
2
what you are looking for is a association via third table yii provides method for this here is an example
class Course extends ActiveRecord
{
// ...
public function getStudents()
{
return $this->hasMany(Student::className(), ['id' => 'student_id'])
->viaTable('student_in_course', ['course_id' => 'id']);
}
// ...
}
class Student extends ActiveRecord
{
// ...
public function getCourses()
{
return $this->hasMany(Course::className(), ['id' => 'course_id'])
->viaTable('student_in_course', ['student_id' => 'id']);
}
// ...
}
please take a look at the guides to get a better understanding
http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#junction-table