You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 22:01:02