簡體   English   中英

Rails查找具有多個關聯記錄的記錄

[英]Rails find record with multiple associated records

假設我有一個Teacher模型,該模型通過class_listings包含了很多學生,包括Teacher_id和Student_id:

class Teacher < ActiveRecord::Base
  has_many :class_listings
  has_many :students, through: :class_listings
end

class ClassListing < ActiveRecord::Base
  belongs_to :teacher
  belongs_to :student
end

class Student < ActiveRecord::Base
  has_many :class_listings
  has_many :teachers, through: :class_listings
end

並且存在:

  • 老師1有學生1
  • 老師2有學生2
  • 老師3有學生1和學生2

我如何查詢有學生1和學生2的老師?

我試過了

Teacher.joins(:class_listings).where(class_listings: {student_id: [1,2]})

但這會返回擁有學生1或2的老師(即老師1、2和3),而不是擁有學生1 2的老師(即老師3)。

假設您的課程清單是唯一的,您也可以這樣:

student_ids = [1, 2]
Teacher.where(
  id: Rel.select(:teacher_id).group(:teacher_id).where(student_id: student_ids)
    .having("count(student_id) = ?", student_ids.count)
)

SQL是:

SELECT "teachers".* FROM "teachers" WHERE "teachers"."id" IN (
  SELECT "rels"."teacher_id" FROM "rels" WHERE "rels"."student_id" IN (1, 2)
  GROUP BY "rels"."teacher_id" HAVING count(student_id) = 2
)

PS:我使用Rel模型而不是ClassListing ,抱歉
PPS:我也喜歡@histocrat的解決方案。

好尷尬 這是不編寫直接SQL的一種方法:

Teacher.where(id: ClassListing.where(student_id: 1).select(:teacher_id))
       .where(id: ClassListing.where(student_id: 2).select(:teacher_id))

它由多個where子句組成,但實際上只會進行一個SQL查詢,例如Select * from teachers where id in (Select teacher_id from ClassListing where student_id = 1) AND id in (Select teacher_id from ClassListing where student_id = 2)

暫無
暫無

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

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