简体   繁体   English

如何在多对多关系sqlalchemy中相交值?

[英]How to intersect values in many-to-many relationship sqlalchemy?

I have table Teacher .我有表Teacher It contains many-to-many relationship with table Student .它包含与表Student的多对多关系。 Student contains unique column name .学生包含唯一的列name how can I find all the teachers that contain students with certain names?我怎样才能找到所有包含某些名字的学生的老师?
For example:例如:
Teacher1 contains Student1 with name "Bob" and Student2 with name "Alice". Teacher1 包含名为“Bob”的 Student1 和名为“Alice”的 Student2。
Teacher2 contains Student2 with name "Alice" and Student3 with name "Mark". Teacher2 包含名为“Alice”的 Student2 和名为“Mark”的 Student3。
Teacher3 contains Student1 with name "Bob". Teacher3 包含名为“Bob”的 Student1。
Teacher4 contains Student3 with name "Mark". Teacher4 包含名为“Mark”的 Student3。
I get names ["Alice", "Mark"] .我得到名字["Alice", "Mark"]
In this example I have to get Teacher 1, 2, 4.在这个例子中,我必须得到教师 1、2、4。
How to write this sqlalchemy query?如何编写这个 sqlalchemy 查询?
session.query(Teacher).filter(...).all() ? session.query(Teacher).filter(...).all()

Asumming that your association many-to-many model/tabele is StudentTeacher and you looking for names=("Alice", "Mark",) , this query should return what you expected:假设您的关联多对多模型/表格是StudentTeacher并且您正在寻找names=("Alice", "Mark",) ,这个查询应该返回您所期望的:

results = session.query(
   Teacher
).join(StudentTeacher).join(Student).filter(
   Student.name.in_(names)
).all()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM