簡體   English   中英

與 SQLAlchemy 上的復合鍵的多對多關系

[英]Many to many relationship with a composite key on SQLAlchemy

假設我有以下模型:

class Molecule(Base):
   db = Column(Integer, primary_key=True)
   id = Column(Integer, primary_key=True)
   data = Column(Integer)

class Atom(Base):
   id = Column(Integer, primary_key=True)
   weight = Column(Integer)

我想在 Molecule 和 Atom 之間建立多對多關系,最好的方法是什么? 注意 Molecule 的主鍵復合的

謝謝

多對多關聯表應該這樣定義:

molecule2atom = Table(
  'molecule2atom',
  Base.metadata, 
  Column('molecule_db', Integer),
  Column('molecule_id', Integer),
  Column('atom_id', Integer, ForeignKey('atom.id')),
  ForeignKeyConstraint( 
    ('molecule_db', 'molecule_id'),
    ('molecule.db', 'molecule.id')  ),
)

並像往常一樣將關系添加到模型之一,例如,在 Class Atom 添加:

molecules = relationship("Molecule", secondary=molecule2atom, backref="atoms")

我更喜歡這里給出的解決方案 - 多對多組合鍵

如果您使用關聯表或完全聲明的表元數據,則可以在兩列中使用primary_key=True ,如建議here

關聯表示例:

employee_role = db.Table(
    "employee_role",
    db.Column("role_id", db.Integer, db.ForeignKey("role.id"), primary_key=True),
    db.Column("employee_id", db.Integer, db.ForeignKey("agent.id"), primary_key=True),
)

元數據示例:

# this is using SQLAlchemy
class EmployeeRole(Base):
    __tablename__ = "employee_role"

    role_id = Column(Integer, primary_key=True)
    employee_id = Column(Integer, primary_key=True)

# this is using Flask-SQLAlchemy with factory pattern, db gives you access to all SQLAlchemy stuff
class EmployeeRole(db.Model):
    __tablename__ = "employee_role"

    role_id = db.Column(db.Integer, primary_key=True)
    employee_id = db.Column(db.Integer, primary_key=True)

它的 Alembic 遷移:

op.create_table(
        'employee_role',
        sa.Column('role_id', sa.Integer(), nullable=False),
        sa.Column('employee_id', sa.Integer(), nullable=False),
        sa.PrimaryKeyConstraint('role_id', 'employee_id')
    )

查詢語句:

CREATE TABLE agent_role (
    role_id INTEGER NOT NULL, 
    employee_id INTEGER NOT NULL, 
    PRIMARY KEY (role_id, employee_id)
);

在關系方面,在一側聲明它(這應該給你role.employeesemployee.roles ,它應該返回一個list ):

# this is using Flask-SQLAlchemy with factory pattern, db gives you access to all SQLAlchemy stuff
class Employee(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    roles = db.relationship("Role", secondary=employee_role, backref="employee")

您的角色類可以是:

# this is using Flask-SQLAlchemy with factory pattern, db gives you access to all SQLAlchemy stuff
class Role(db.Model):
    __tablename__ = "role"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(25), nullable=False, unique=True)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM