繁体   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