簡體   English   中英

sqlalchemy-與association_table聯接

[英]sqlalchemy - join with association_table

我有2個表(對象)和關聯表:

association_table = Table('association', Base.metadata,
    Column('left_id', Integer, ForeignKey('left.id')),
    Column('right_id', Integer, ForeignKey('right.id'))
)

class Parent(Base):
    __tablename__ = 'left'
    id = Column(Integer, primary_key=True)
    children = relationship("Child",
                    secondary=association_table,
                    backref="parents")

class Child(Base):
    __tablename__ = 'right'
    id = Column(Integer, primary_key=True)

當我用join執行查詢時,出現此錯誤:

session.query(Child).join(Parent)
InvalidRequestError: Could not find a FROM clause to join from.  Tried joining to <class '__main__.Parent'>, but got: Can't find any foreign key relationships between 'right' and 'left'

但是每個對象都有另一個表中相對對象的引用:

print session.query(Child,Parent).filter(Child.parents.any(id = 2))
SELECT "right".id AS right_id, "left".id AS left_id 
FROM "right", "left" 
WHERE EXISTS (SELECT 1 
FROM association, "left" 
WHERE "right".id = association.right_id AND "left".id = association.left_id AND "left".id = :id_1)

問題#1:為什么sqlalchemy可以找出使用關聯表的方法,卻無法以相同的方式聯接。

問題2:什么是正確的方法? 我嘗試了這個:

print session.query(Child).join(Child.parents)
SELECT "right".id AS right_id 
FROM "right" JOIN association AS association_1 ON "right".id = association_1.right_id JOIN "left" ON "left".id = association_1.left_id

但我不確定這是最好的方法。 我應該設置primaryjoin \\ secondaryjoin參數嗎?

在第一次嘗試時,您應該仔細閱讀錯誤:

找不到“右”和“左”之間的任何外鍵關系

ChildParent之間沒有直接的外鍵關系,因此您可以在以下之間添加關聯表:

session.query(Child).join(association_table).join(Parent)`

session.query(Child, Parent)

是2之間的交叉聯接 ,可能不是您的意思。 它將每個Parent連接到每個與WHERE子句條件匹配的Child

您的“問題2”是正確的處理方式,在SQLAlchemy中被稱為“ 關系聯接”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM