Flask/SQLAlchemy - 多对多关系的关联模型和关联 table 之间的区别?

Flask/SQLAlchemy - Difference between association model and association table for many-to-many relationship?

我是从 Flask Mega 教程开始学习这些东西的。当他进入多对多关系时,他创建了一个关联 table,如下所示:

followers = db.Table('followers',
    db.Column('follower_id', db.Integer, db.ForeignKey('user.id')),
    db.Column('followed_id', db.Integer, db.ForeignKey('user.id'))
)

当我正在寻找添加一些关于模型之间特定关联的元数据的方法时,我发现您可以将这种东西存储在关联中 table。但是我找到了这个例子似乎使关联 table 成为实际模型。

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"))

这两种方法有什么区别?模型方法是否需要在关联中存储元数据table 还是可以使用 top 方法完成同样的事情?

谢谢!

抱歉,我终于在 SQLAlchemy 文档中找到了答案...

https://docs.sqlalchemy.org/en/latest/orm/basic_relationships.html#many-to-many

...他们明确定义差异的地方:

Many to Many adds an association table between two classes.

association_table = Table('association', Base.metadata,
    Column('left_id', Integer, ForeignKey('left.id')),
    Column('right_id', Integer, ForeignKey('right.id'))
)

The association object pattern is a variant on many-to-many: it’s used when your association table contains additional columns beyond those which are foreign keys to the left and right tables. Instead of using the secondary argument, you map a new class directly to the association table.

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'))

其中"Right"和"Left"是table,正常定义:

class Left(Base):
    __tablename__ = 'left'
    id = Column(Integer, primary_key = True)
    ...

class Right(Base):
    __tablename__ = 'right'
    id = Column(Integer, primary_key = True)
    ...

所以如果你需要在关联中存储任何东西,它基本上是创建一个关联对象来引用这个额外的信息,否则就没有必要使用 ORM 层,你可以只创建一个关联 table。