从 2 个表中获取数据的最佳 Yii 方法是什么?
What's the best Yii way of getting data from 2 tables?
我想获取基于 2 个数据库表的数据
有:
course table
student_in_course table (with foreign key course_id)
我想要全部course.name
基于student_in_course.course_id
对于特定的 student_in_course.student_id
使用 ActiveRecord(或其他推荐的方式)执行此操作的最佳做法是什么?
提前致谢
Yii2 文档建议使用 'joinWith' 以防您需要使用 Active record 执行左连接查询。所以在你的情况下你会想要这样的东西:
$courses = Course::find()
->select('course.name')
->joinWith('student_in_course')
->where(['student_in_course.student_id' => $student_id])
->all();
是的,ActiveRecord
是我更喜欢用它来做的,但问题是如果你打算在某个时候使用 activeDataProvider
在 GridView
或 ListView
中显示您可能需要更新/调整 serachModel 中的查询,而不是在 model
中编写带有查询的单独函数,或者像某些人在控制器的操作中写的那样,除非您使用自定义视图并手动显示它并希望结果集作为 array
或 activedataprovider
对象对其进行迭代并显示记录,然后 @GiulioG
建议的答案适用。但是在这两种情况下都需要注意的是,您应该定义适当的relations
,而不需要手动使用joins
。
首先,如果您要使用 YII,ActiveRecord 是最好的方法,似乎您要使用交叉引用 table 使用 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');
}
}
我想获取基于 2 个数据库表的数据
有:
course table
student_in_course table (with foreign key course_id)
我想要全部course.name
基于student_in_course.course_id
对于特定的 student_in_course.student_id
使用 ActiveRecord(或其他推荐的方式)执行此操作的最佳做法是什么?
提前致谢
Yii2 文档建议使用 'joinWith' 以防您需要使用 Active record 执行左连接查询。所以在你的情况下你会想要这样的东西:
$courses = Course::find()
->select('course.name')
->joinWith('student_in_course')
->where(['student_in_course.student_id' => $student_id])
->all();
是的,ActiveRecord
是我更喜欢用它来做的,但问题是如果你打算在某个时候使用 activeDataProvider
在 GridView
或 ListView
中显示您可能需要更新/调整 serachModel 中的查询,而不是在 model
中编写带有查询的单独函数,或者像某些人在控制器的操作中写的那样,除非您使用自定义视图并手动显示它并希望结果集作为 array
或 activedataprovider
对象对其进行迭代并显示记录,然后 @GiulioG
建议的答案适用。但是在这两种情况下都需要注意的是,您应该定义适当的relations
,而不需要手动使用joins
。
首先,如果您要使用 YII,ActiveRecord 是最好的方法,似乎您要使用交叉引用 table 使用 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');
}
}