shop_platform - 建立多對多關聯:Association Object

根據 SQLAlchemy 的 Basic Relationship Patterns,建立多對多關聯有兩種方式:

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

Popular posts from this blog

資料關聯

程式設計相關社群、活動

TCP/ IP 通訊協定