gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 04:45:03 25 4
gpt4 key购买 nike

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

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 方法完成同样的事情吗?

谢谢!

最佳答案

抱歉,我终于在 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”是表格,通常定义:

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

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

因此,如果您需要在关联中存储任何内容,那么它基本上是创建一个关联对象来引用这些额外信息,否则没有必要使用 ORM 层,您只需创建一个关联表即可。

关于Flask/SQLAlchemy - 多对多关系的关联模型和关联表之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30406808/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com