简体   繁体   English

sqlalchemy-与association_table联接

[英]sqlalchemy - join with association_table

i have 2 tables (objects), and 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)

when i perform a query with join i get this error: 当我用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'

but there is reference in each object to it's relative objects in the other table: 但是每个对象都有另一个表中相对对象的引用:

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)

question #1: why while sqlalchemy can figure out the way to use the association table, it failed to join in the same way. 问题#1:为什么sqlalchemy可以找出使用关联表的方法,却无法以相同的方式联接。

question #2: whats the proper way to do it. 问题2:什么是正确的方法? i tried this: 我尝试了这个:

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

but i'm not sure it's the best way. 但我不确定这是最好的方法。 should i set primaryjoin\\secondaryjoin params? 我应该设置primaryjoin \\ secondaryjoin参数吗?

In your first attempt you should read the error carefully: 在第一次尝试时,您应该仔细阅读错误:

Can't find any foreign key relationships between 'right' and 'left' 找不到“右”和“左”之间的任何外键关系

There are no direct foreign key relationships between Child and Parent , so you'd add the association table between: ChildParent之间没有直接的外键关系,因此您可以在以下之间添加关联表:

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

The

session.query(Child, Parent)

is a cross join between the 2 and probably not what you meant. 是2之间的交叉联接 ,可能不是您的意思。 It joins every Parent to every Child that matches the WHERE clause criterion. 它将每个Parent连接到每个与WHERE子句条件匹配的Child

Your "question #2" is the right way to do it and known as a relationship join in SQLAlchemy parlance. 您的“问题2”是正确的处理方式,在SQLAlchemy中被称为“ 关系联接”。

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

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