在PostgreSql中有关联的子句

这是我的关联

Instructor has many Instructor Students InstructorStudent has many Student Contacts 

Student Contacts表有一个字段primary_contact,它有布尔类型。

我希望没有任何学生联系人或所有学生联系人的primary_contact的教师学生都是假的。

例如

教师学生1有3个学生联系人,所有3个学生联系人的主要联系人字段都是假的。 比我想要的记录

教师学生2有3个学生联系人,其中2个学生联系人的主要联系人字段是假的,而其他学生联系人的主要联系人是真实的,而不是我不想要该记录。

我做了一个查询,但我不怎么写有条款。

Instructor.joins(:instructor_students => :student_contacts) .where("admin_users.id = ? AND student_contacts.primary_contact = ?",7,false) .select("student_contacts.instructor_student_id,count(student_contacts.primary_contact) as sc_count") .group("student_contacts.instructor_student_id") .having("count(student_contacts.primary_contact) = ?",Dynamic_value)

任何帮助将不胜感激。 先感谢您。

请试试这个,因为你说你想要InstructorStudent对象所以你应该加入那个表。

 InstructorStudent.joins(:student_contacts).where("student_contacts.primary_contact = ?",false) .select("student_contacts.instructor_student_id,count(student_contacts.primary_contact) as sc_count") .group("student_contacts.instructor_student_id") .having("count(student_contacts.primary_contact) = ?",Dynamic_value)