# Tables
Base = declarative_base()
class Company(Base):
__tablename__ = "company"
id = Column(Integer, primary_key=True)
class Employee(Base): __tablename__ = "employee"
id = Column(Integer, primary_key=True)
first_company_id = Column(Integer, ForeignKey("company.id"))
second_company_id = Column(Integer, ForeignKey("company.id"))
first_company = relationship("Company", foreign_keys=first_company_id)
second_company = relationship("Company", foreign_keys=second_company_id)
# Application code
child_alias = aliased(Company)
parent_alias = aliased(Employee)
query = session.query(parent_alias)
join = join(parent_alias, child_alias) # Throws multiple join paths exception (works fine if there is only one relationship to Company)
extra_on_clause = (1 == 1)
query = query.join(
parent_alias,
and_(join.onclause, extra_on_clause),
)
# Can't use this because it doesn't allow extra clauses
query.join(parent_alias.first_company)
# Can't use this because I don't know the join expression (unknown part in bold)
query = query.join(
parent_alias,
and_(parent_alias.first_company_id == child_alias.id, extra_on_clause),
)
# Almost produces the correct join clause except that the company.id is the wrong alias
onclause = parent_alias.first_company.expression # company.id = employee_1.first_company_id
company_1.id = employee_1.first_company_id
--SQLAlchemy -The Python SQL Toolkit and Object Relational MapperTo post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description.---You received this message because you are subscribed to the Google Groups "sqlalchemy" group.To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+...@googlegroups.com.To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/90940889-2a85-4e6f-9c89-bb52d305b85d%40googlegroups.com.
This is exactly what I was looking for! That's amazing, thank you very much. I wasn't aware you could pass a relationship to the onclause parameter of the join() function which I am now seeing is actually in the docs.Cheers!
--SQLAlchemy -The Python SQL Toolkit and Object Relational MapperTo post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description.---You received this message because you are subscribed to the Google Groups "sqlalchemy" group.To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/f1981a14-27c7-4701-ba0d-17c7a0ea41ae%40googlegroups.com.