我有 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 参数吗?
最佳答案
在您第一次尝试时,您应该仔细阅读错误:
Can't find any foreign key relationships between 'right' and 'left'
Child
之间没有直接的外键关系和 Parent
,因此您将在以下各项之间添加关联表:session.query(Child).join(association_table).join(Parent)`
这
session.query(Child, Parent)
是 cross join在 2 之间,可能不是你的意思。它连接每个
Parent
到每个 Child
匹配 WHERE 子句标准。您的“问题 #2”是正确的方法,被称为 relationship join在 SQLAlchemy 中。
关于python - sqlalchemy - 加入 association_table,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49802004/