如何在SQLAlchemy中使用association_table获取多对多关系中的所有行?

问题描述 投票:0回答:1

我有下面显示的表格,并尝试在单个

children
行中返回
parent
,以便我可以迭代它们而不获取
parent
行。

sub = select(Parent.children).where(Parent.id == 1).subquery()
children = select(Child).where(Child.id.in_(sub))

我做错了什么?

来源:https://docs.sqlalchemy.org/en/20/orm/basic_relationships.html#many-to-many

association_table = Table(
    "association_table",
    Base.metadata,
    Column("left_id", ForeignKey("left_table.id")),
    Column("right_id", ForeignKey("right_table.id")),
)

class Parent(Base):
    __tablename__ = "left_table"

    id: Mapped[int] = mapped_column(primary_key=True)
    children: Mapped[List[Child]] = relationship(secondary=association_table)


class Child(Base):
    __tablename__ = "right_table"

    id: Mapped[int] = mapped_column(primary_key=True)
sqlalchemy many-to-many
1个回答
0
投票

与其试图通过

Parent
,不如直接使用关联表:

with Session() as s:
    sub = sa.select(association_table.c.right_id).where(association_table.c.left_id == 1).subquery()
    children = sa.select(Child).where(Child.id.in_(sub))
    for child in s.scalars(children):
        print(child)

或者,添加与子模型的关系


class Child(Base):
    ...
    parents: Mapped[List[Parent]] = orm.relationship(secondary=association_table, back_populates='children')

并用它来访问孩子们:

with Session() as s:
    children = sa.select(Child).where(Child.parents.any(Parent.id == 1))
    for child in s.scalars(children):
        print(child)
© www.soinside.com 2019 - 2024. All rights reserved.