简体   繁体   中英

sqlalchemy - join with association_table

i have 2 tables (objects), and association table:

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:

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.

question #2: whats the proper way to do it. 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?

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:

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. It joins every Parent to every Child that matches the WHERE clause criterion.

Your "question #2" is the right way to do it and known as a relationship join in SQLAlchemy parlance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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