我开始从Flask Mega Tutorial中学习这些东西。当他进入多对多关系时,他会创建一个这样的关联表:
followers = db.Table('followers',
db.Column('follower_id', db.Integer, db.ForeignKey('user.id')),
db.Column('followed_id', db.Integer, db.ForeignKey('user.id'))
)
当我在寻找添加一些关于模型之间特定关联的元数据的方法时,我发现你可以在关联表中存储这种东西。但是我发现的这个例子似乎使得关联表一个实际的模型。
class DepartmentEmployeeLink(Base):
__tablename__ = 'department_employee_link'
department_id = Column(Integer, ForeignKey('department.id'), primary_key=True)
employee_id = Column(Integer, ForeignKey('employee.id'), primary_key=True)
extra_data = Column(String(256))
department = relationship(Department, backref=backref("employee_assoc"))
employee = relationship(Employee, backref=backref("department_assoc"))
这两种方法有什么区别?将元数据存储在关联表中是否需要模型方法,或者使用top方法可以完成同样的事情吗?
谢谢!
答案 0 :(得分:24)
道歉,我终于在SQLAlchemy文档中偶然发现了答案......
https://docs.sqlalchemy.org/en/latest/orm/basic_relationships.html#many-to-many
...他们明确定义差异:
Many to Many在两个类之间添加了一个关联表。
association_table = Table('association', Base.metadata,
Column('left_id', Integer, ForeignKey('left.id')),
Column('right_id', Integer, ForeignKey('right.id'))
)
关联对象模式是多对多的变体:它被使用 当您的关联表包含超出这些列的其他列时 这是左右表的外键。而不是使用 辅助参数,您将新类直接映射到 协会表。
class Association(Base):
__tablename__ = 'association'
left_id = Column(Integer, ForeignKey('left.id'), primary_key=True)
right_id = Column(Integer, ForeignKey('right.id'), primary_key=True)
extra_data = Column(String(50))
left = relationship('Left', backref=backref('right_association'))
right = relationship('Right', backref=backref('left_association'))
在哪里"对"和"左"是正常定义的表:
class Left(Base):
__tablename__ = 'left'
id = Column(Integer, primary_key = True)
...
class Right(Base):
__tablename__ = 'right'
id = Column(Integer, primary_key = True)
...
因此,如果您需要在关联中存储任何内容,它基本上创建一个关联对象来引用这些额外信息,否则它不需要使用ORM层,您只需创建一个关联表。