PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, March 4, 2022

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

 March 04, 2022     active-record-query, mysql, php, yii, yii2     No comments   

Issue

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.



Answered By - GiulioG
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing