简体   繁体   中英

How to intersect values in many-to-many relationship sqlalchemy?

I have table Teacher . It contains many-to-many relationship with table Student . Student contains unique column 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".
Teacher2 contains Student2 with name "Alice" and Student3 with name "Mark".
Teacher3 contains Student1 with name "Bob".
Teacher4 contains Student3 with name "Mark".
I get names ["Alice", "Mark"] .
In this example I have to get Teacher 1, 2, 4.
How to write this sqlalchemy query?
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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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