![](/img/trans.png)
[英]SQLAlchemy - Problem with an association table and dates in primary join
[英]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参数吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.