簡體   English   中英

從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_idstudent_in_course.student_id

使用ActiveRecord(或其他推薦方式)執行此操作的最佳做​​法是什么?

提前致謝

首先,如果您要使用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文檔建議使用'joinWith',以防您需要對Active Record執行左聯接查詢。 因此,在您的情況下,您需要這樣的東西:

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

請參考Yii2官方文檔

是的, ActiveRecord是我更喜歡的方法,但是事情是,如果您打算在activeDataProvider時候使用activeDataProviderGridViewListView顯示,則可能需要在serachModel中更新/調整查詢,而不是在查詢中編寫單獨的函數model或某些人確實在控制器的動作中編寫的方法,直到除非您使用自定義視圖並手動顯示它,並希望結果集作為arrayactivedataprovider對象在其上進行迭代並顯示記錄,然后@GiulioG建議答案適用。 但是,在這兩種情況下都需要注意的是,您應該定義適當的relations並且不需要手動使用joins

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM