[英]What's the best Yii way of getting data from 2 tables?
I want to get data based on 2 db tables 我想基于2个数据库表获取数据
There is: 有:
course table
student_in_course table (with foreign key course_id)
I would like to get all course.name
我想获得所有的course.name
based on student_in_course.course_id
for a specific student_in_course.student_id
基于student_in_course.course_id
的student_in_course.student_id
What's the best practice of doing it with ActiveRecord (or other recommended way)? 使用ActiveRecord(或其他推荐方式)执行此操作的最佳做法是什么?
Thanks in advance 提前致谢
First of all, ActiveRecord is the best approach if you are going to work with YII, seems like you are going to use a cross-reference table use via()
or viaTable()
. 首先,如果您要使用YII,ActiveRecord是最好的方法,似乎您将要使用交叉引用表使用via()
或viaTable()
。
class Student extends ActiveRecord{
public function getStudentsInCourses() {
return $this->hasMany(StudentInCourses::className(), ['student_id' => 'id']);
}
public function getCourses() {
return $this->hasMany(Course::className(), ['id' => course_id'])
->via('studentsInCourses');
}
}
Yii2 documentation suggests to use 'joinWith' in case you need to perform a left join query with Active record. Yii2文档建议使用'joinWith',以防您需要对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 . 请参考Yii2官方文档 。
Yes, ActiveRecord
is what I would prefer doing it with,but the thing is if you are going to display in GridView
or ListView
using activeDataProvider
sometime you might need to update/ adjust the query in serachModel rather than writing a separate function with a query in the model
or as some people do write inside controller's action, until unless if you are using a custom view and displaying it manually and want the result set as an array
or activedataprovider
object to iterate on it and display records then the answer suggested by @GiulioG
is applicable. 是的, ActiveRecord
是我更喜欢的方法,但是事情是,如果您打算在activeDataProvider
时候使用activeDataProvider
在GridView
或ListView
显示,则可能需要在serachModel中更新/调整查询,而不是在查询中编写单独的函数model
或某些人确实在控制器的动作中编写的方法,直到除非您使用自定义视图并手动显示它,并希望结果集作为array
或activedataprovider
对象在其上进行迭代并显示记录,然后@GiulioG
建议答案适用。 But the thing to be noticed in both the scenarios is that you should define appropriate relations
and you do not need to use joins
manually. 但是,在这两种情况下都需要注意的是,您应该定义适当的relations
并且不需要手动使用joins
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.