簡體   English   中英

sqlalchemy通過關聯代理連接多個條件

[英]sqlalchemy multiple join conditions through association proxy

我有三個結構,在它們之間的每個可能的關系點都有數據(稱為a,b和c)。 我聲明這些關系(與關聯的表)如此...

class A(Base):
    __tablename__ = 'a'

    id            = Column( types.Integer(), primary_key = True )

    abs           = orm.relation( 'AB' )
    acs           = orm.relation( 'AC' )

# similarly for b and c

class AB(Base):
    __tablename__ = 'ab'

    id            = Column( types.Integer(), primary_key = True )
    a_id          = Column( types.Integer(), ForeignKey( 'a.id' ) )
    b_id          = Column( types.Integer(), ForeignKey( 'b.id' ) )

    a             = orm.relation( 'A' )
    b             = orm.relation( 'B' )

    abcs          = orm.relation( 'ABC' )
    acs           = association_proxy( 'abcs', 'ac' )

# similarly for ac

class ABC(Base):
    __tablename__ = 'abc'

    id            = Column( types.Integer(), primary_key = True )
    ab_id         = Column( types.Integer(), ForeignKey( 'ab.id' ) )
    ac_id         = Column( types.Integer(), ForeignKey( 'ac.id' ) )

    ab            = orm.relation( 'AB' )
    ac            = orm.relation( 'AC' )

現在,以下代碼失敗:

abs = db.session.query( AB ).join( A ).join( AC ).join( C ).join( B ).join( ABC, and_(
    ABC.ab_id == AB.id,
    ABC.ac_id == AC.id
) ).all()

以上產生以下錯誤:

ArgumentError:無法確定在連接對象上的連接對象上的連接對象,連接對象上的連接對象(163066988)和一個(162822028)(175636236)和交流(162854924)(2936229868)和c(161105164)( 2936272780)'和'abc'; 表之間有多個外鍵約束關系。 請明確指定此聯接的“onclause”。

似乎SQLAlchemy不支持自動加入或通過指定多個連接條件。 執行此操作的正確方法是使用其中一個自動連接(例如AB.abcs )並將其他條件指定為過濾器。

abs = db.session.query( AB ).join( AB.a ).join( A.acs ).join( AC.c )\
    .join( AB.b ).join( AB.abcs ).filter( ABC.ac_id = AC.id ).all()

暫無
暫無

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

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