如何在SQLAlchemy中通过association_table获取指定父行的所有子行?
问题分析与解决
你出错的核心原因是:Parent.children是ORM层面定义的关系属性,并非数据库表的实际列,不能直接放到select()语句中作为查询字段使用。
正确的实现方式有以下几种:
方法1:通过关联表直接JOIN查询(最直观高效)
直接将Child表与关联表关联,过滤出对应Parent的记录:
children = select(Child).join(association_table).where(association_table.c.left_id == 1)
方法2:使用EXISTS子查询
通过存在性判断筛选关联的Child:
from sqlalchemy import exists children = select(Child).where( exists( select(association_table.c.right_id) .where(association_table.c.left_id == 1) .where(association_table.c.right_id == Child.id) ) )
方法3:利用ORM关系的JOIN查询
借助Parent与Child的关系定义完成关联:
children = select(Child).select_from( Parent.join(Parent.children) ).where(Parent.id == 1)
以上三种方式都能直接获取到id为1的Parent对应的所有Child记录,且不会查询Parent本身。
内容的提问来源于stack exchange,提问作者Aage Torleif
相关产品推荐
相关产品推荐

