0

有一个 sqlalchemy 对象

class Employee(Base):
    __tablename__ = "employee"
    # Columns
    id = Column(Integer, primary_key=True, autoincrement=True)
    representative_id = Column(Integer, ForeignKey('employee.id'))
    parent_id = Column(Integer, ForeignKey('employee.id'))
    affiliate_id = Column(Integer, ForeignKey('employee.id'))

    # Relatonships
    representative = relationship("Employee", ????)
    parent = relationship("Employee", ????)
    affiliate = relationship("Employee", ????)

如果员工可以有 0 个或 1 个父母、附属机构和代表,如何以正确的方式配置关系?知道这三个是不同的。数据库 - MySQL

4

1 回答 1

1

我自己发现了如何做到这一点:

class Employee(Base):
    __tablename__ = "employee"
    # Columns
    id = Column(Integer, primary_key=True, autoincrement=True)
    representative_id = Column(Integer, ForeignKey('employee.id'))
    parent_id = Column(Integer, ForeignKey('employee.id'))
    affiliate_id = Column(Integer, ForeignKey('employee.id'))

    # Relatonships
    representative = relationship("Employee", 
                         primaryjoin="Employee.representative_id==Employee.id", 
                         remote_side=[id])
    parent = relationship("Employee",
                         primaryjoin="Employee.parent_id==Employee.id", 
                         remote_side=[id])
    affiliate = relationship("Employee",
                         primaryjoin="Employee.affiliate_id==Employee.id", 
                         remote_side=[id])
于 2012-05-23T17:09:32.777 回答