shop_platform - 建立多對多關聯:Association Object
根據 SQLAlchemy 的 Basic Relationship Patterns,建立多對多關聯有兩種方式:
join table 上只有外鍵欄位:使用 association table
join table 上除了外鍵,還有其他欄位:使用 association object
association object 不同欄位間的關係:
class Association(Base):
__tablename__ = 'association'
left_id = Column(ForeignKey('left.id'), primary_key=True)
right_id = Column(ForeignKey('right.id'), primary_key=True)
extra_data = Column(String(50))
child = relationship("Child", back_populates="parents")
parent = relationship("Parent", back_populates="children")
class Parent(Base):
__tablename__ = 'left'
id = Column(Integer, primary_key=True)
children = relationship("Association", back_populates="parent")
class Child(Base):
__tablename__ = 'right'
id = Column(Integer, primary_key=True)
parents = relationship("Association", back_populates="child")
若是使用 flask_sqlalchemy 套件的話,上述程式碼中的:
Base 改成 db.Model
Column 改成 db.Column
ForeignKey 改成 db.ForeignKey
String 改成 db.String,Integer 改成 db.Integer
relationship 改成 db.relationship
commit: feat: add CartItem model
參考資料
Comments
Post a Comment