我有下面显示的表格,并尝试在单个
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)
与其试图通过
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)