SQLAlchemy 错误映射类在加入多个关系时不适用于此查询中的任何根实体

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

我正在尝试加入 3 个表,例如:

stmt = stmt.join(Child.parent).join(Parent.grandparent)
stmt = stmt.options(
    contains_eager(Child.parent).contains_eager(Parent.grandparent),
)

但是当我这么做的时候,我就明白了

Mapped class Mapper[Parent(parents)] does not apply to any of the root entities in this query, e.g. Mapper[Child(children)]. Please specify the full path from one of the root entities to the target attribute.

型号:

class Child(Base):
    __tablename__ = "children"

    parent_id: Mapped[int] = mapped_column(
        ForeignKey(
            "parents.id",
            ondelete="CASCADE",
        )
    )
    parent: Mapped["Parent"] = relationship(lazy="joined", innerjoin=True)

class Parent(Base):
    __tablename__ = "parents"

    gramdparent_id: Mapped[str] = mapped_column(
        ForeignKey(
            "grandparents.id",
            ondelete="CASCADE",
        ),
    )
    grandparent: Mapped["Grandparent"] = relationship(lazy="joined", innerjoin=True)

class Grandparent(Base):
    __tablename__ = "grandparents"
    ...
sqlalchemy
1个回答
0
投票

意识到它是因为我在相关桌子上做了

selectinload

stmt = stmt.join(Child.parent).join(Parent.grandparent)
stmt = stmt.options(
    contains_eager(Child.parent).contains_eager(Parent.grandparent),
    selectinload(Parent.tags) # This
)

应该是

stmt = stmt.join(Child.parent).join(Parent.grandparent)
stmt = stmt.options(
    contains_eager(Child.parent).contains_eager(Parent.grandparent),
    contains_eager(Child.parent).selectinload(Parent.tags)
)

© www.soinside.com 2019 - 2024. All rights reserved.