Search code examples
phpmysqlyiiyii2active-record-query

What's the best Yii way of getting data from 2 tables?


I want to get data based on 2 db tables

There is:

 course table
 student_in_course table (with foreign key course_id)

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 practice of doing it with ActiveRecord (or other recommended way)?

Thanks in advance


Solution

  • Yii2 documentation suggests to use 'joinWith' in case you need to perform a left join query with Active record. So in your case you'd want something like this:

    $courses = Course::find()
      ->select('course.name')
      ->joinWith('student_in_course')
      ->where(['student_in_course.student_id' => $student_id])
      ->all();
    

    Please refer to Yii2 official docs.