sqlalchemy - 与association_table一起加入

时间:2018-04-12 16:47:37

标签: python join sqlalchemy

我有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 params吗?

1 个答案:

答案 0 :(得分:0)

在您第一次尝试时,您应该仔细阅读错误:

  

无法找到&#39;对&#39;之间的任何外键关系。和&#39;离开&#39;

ChildParent之间没有直接的外键关系,因此您可以在以下位置添加关联表:

session.query(Child).join(association_table).join(Parent)`

session.query(Child, Parent)

是2之间的cross join,可能不是你的意思。它将每个Parent连接到与WHERE子句标准匹配的每个Child

你的问题#2&#34;是正确的方法,在SQLAlchemy用语中称为relationship join