繁体   English   中英

如何在 SQL Alchemy 中为多对多关系添加连接条件?

[英]How do I add join conditions on many to many relationships in SQL Alchemy?

我有模型AB ,使用参考模型AB (关联表)的secondary参数以多对多关系连接。

使用query(A).options(joinedload(Ab))将生成查询:

SELECT ...
FROM a
LEFT OUTER JOIN (a_b AS a_b_1 JOIN b ON b.id = a_b_1.b_id) ON a.id = a_b_1.a_id

但我想要额外的连接条件(不使用 WHERE!),以便过滤B的某个标志。 所以就像这样:

SELECT ...
FROM a
LEFT OUTER JOIN (a_b AS a_b_1 JOIN b ON b.id = a_b_1.b_id AND b.flag = 1) ON a.id = a_b_1.a_id

我如何使用 SQL Alchemy 做到这一点?

您可以使用and_().outerjoin表达()。 只是一个有 2 个模型的例子:

from sqlalchemy import and_

class A(Base):
    __tablename__ = 'a'
    id = Column(Integer, primary_key=True)


class B(Base):
    __tablename__ = 'b'
    id = Column(Integer, primary_key=True)
    a_id = Column(Integer)
    flag = Column(String)


a = A()
session.add(a)
session.commit()

# just a few records. without flag + with flag
b1 = B(a_id=a.id)
b2 = B(a_id=a.id, flag='Cs_Is_Better')

session.add(b1)
session.add(b2)
session.commit()

query = session.query(A).outerjoin(B, (and_(A.id == B.a_id, B.flag == 'Cs_Is_Better')))

print(query)
# SELECT a.id AS a_id 
# FROM a LEFT OUTER JOIN b ON a.id = b.a_id AND b.flag = %(flag_1)s
print(query.all())  # [<__main__.A object at 0x112fb4780>]

因此,只需向outerjoin添加任何条件:

.outerjoin(ModelName, (and_(...))

希望这可以帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM