简体   繁体   English

sqlalchemy通过关联代理连接多个条件

[英]sqlalchemy multiple join conditions through association proxy

I have three structures with data at each possible relationship point between them (call them a, b, and c). 我有三个结构,在它们之间的每个可能的关系点都有数据(称为a,b和c)。 I declare these relations (with the associated tables) like so... 我声明这些关系(与关联的表)如此...

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' )

Now the following code fails: 现在,以下代码失败:

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()

The above yields the following error: 以上产生以下错误:

ArgumentError: Can't determine join between 'Join object on Join object on Join object on Join object on Join object on ab(163066988) and a(162822028)(175636236) and ac(162854924)(2936229868) and c(161105164)(2936272780)' and 'abc'; ArgumentError:无法确定在连接对象上的连接对象上的连接对象,连接对象上的连接对象(163066988)和一个(162822028)(175636236)和交流(162854924)(2936229868)和c(161105164)( 2936272780)'和'abc'; tables have more than one foreign key constraint relationship between them. 表之间有多个外键约束关系。 Please specify the 'onclause' of this join explicitly. 请明确指定此联接的“onclause”。

It seems that SQLAlchemy doesn't support this kind of joining automatically or via specifying multiple join conditions. 似乎SQLAlchemy不支持自动加入或通过指定多个连接条件。 The correct way to do this is to use one of the automatic joins (eg AB.abcs ) and specify the other condition as a filter. 执行此操作的正确方法是使用其中一个自动连接(例如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