如何在sql炼金术中为多对多关系添加连接条件?

hs1ihplo  于 2021-06-15  发布在  Mysql
关注(0)|答案(1)|浏览(296)

我有模型 A 以及 B ,使用 secondary 参考模型的参数 AB (关联表)。
使用 query(A).options(joinedload(A.b)) 将生成查询:

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炼金术来实现这一点?

6rvt4ljy

6rvt4ljy1#

可以将and()表达式与.outerjoin()一起使用。仅举两种型号的示例:

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

希望这有帮助。

相关问题