【问题标题】:What's the best Yii way of getting data from 2 tables?从 2 个表中获取数据的最佳 Yii 方法是什么?
【发布时间】:2017-12-10 07:38:03
【问题描述】:

我想获取基于 2 个 db 表的数据

有:

 course table
 student_in_course table (with foreign key course_id)

我要全部course.name

基于student_in_course.course_id 对于特定的student_in_course.student_id

使用 ActiveRecord(或其他推荐方式)的最佳做法是什么?

提前致谢

【问题讨论】:

  • 为什么不在SQL语句中做呢?
  • 我是 Yii 的新手,但我看到有很多关于视图的现成方法等等,如果能学习一种新的好方法会很高兴

标签: php mysql yii yii2 active-record-query


【解决方案1】:

首先,如果您要使用 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');
     }
}

【讨论】:

  • +1 voteup ,提及viaTable(),因为它重用了关系并防止您使用额外的 SQL 查询填充您的模型。
【解决方案2】:

Yii2 文档建议使用“joinWith”以防您需要对活动记录执行左连接查询。所以在你的情况下,你需要这样的东西:

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

请参考Yii2 official docs

【讨论】:

    【解决方案3】:

    是的,ActiveRecord 是我更喜欢使用的方式,但问题是,如果您要使用 activeDataProviderGridViewListView 中显示,有时您可能需要更新/调整查询serachModel 而不是在 model 中编写带有查询的单独函数,或者像某些人在控制器的操作中编写的那样,除非您使用自定义视图并手动显示它并且希望结果集为 array 或 @ 987654327@ 对象对其进行迭代并显示记录,然后@GiulioG 建议的答案适用。但是在这两种情况下需要注意的是,您应该定义适当的relations,并且您不需要手动使用joins

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多