如何通过多对多关系link两条已有记录

How to link two existing records through many to many relationship

我需要将 roles 添加到 staff,以下代码有效,但不知何故它不允许将相同的角色添加到多个员工。如果再次分配相同的角色,则先前的分配将从辅助 table 中删除!为什么会这样

staff_roles = Table('staff_roles', Base.metadata,
    Column('staff_id', Integer, ForeignKey('staff.id')),
    Column('role_id', Integer, ForeignKey('roles.id'))
)

class Staff(Base):
    __tablename__="staff"
    id=             Column(Integer, primary_key=True, index=True)
    img=            Column(String)
    civil_id=       Column(Integer)
    nationality=    Column(String)
    disabled=       Column(Boolean, default=False)
    created_at=     Column(DateTime)
    updated_at=     Column(DateTime)

    user_id = Column(Integer, ForeignKey('users.id'), nullable=False)
    roles = relationship("Roles", uselist=True, secondary=staff_roles, back_populates="staff", lazy='raise')



class Roles(Base):
    __tablename__="roles"
    id=             Column(Integer, primary_key=True, index=True)
    name=           Column(String)
    staff = relationship("Staff", uselist=False, secondary=staff_roles, back_populates="roles", lazy='raise')



def add_role_to_staff(db: Session, user_id:int, role_ids:list):
    roles = db.query(tables.Roles).options(joinedload(tables.Roles.staff)).filter(tables.Roles.id.in_(role_ids)).all()
    staff = db.query(tables.Staff).options(joinedload(tables.Staff.roles)).filter(tables.Staff.user_id == user_id).first()
    if len(roles) == 0 or staff is None:
        raise HTTPException(status_code=404, detail="role or staff does not exist")

    for role in roles:
        staff.roles.append(role)
        
    try:
        db.commit()
    except IntegrityError as e:
        db.rollback()
        process_db_error(e)

来自日志:

INFO:sqlalchemy.engine.base.Engine:DELETE FROM staff_roles WHERE staff_roles.staff_id = %(staff_id)s AND staff_roles.role_id = %(role_id)s
INFO:sqlalchemy.engine.base.Engine:{'staff_id': 2, 'role_id': 2}
INFO:sqlalchemy.engine.base.Engine:INSERT INTO staff_roles (staff_id, role_id) VALUES (%(staff_id)s, %(role_id)s)
INFO:sqlalchemy.engine.base.Engine:{'staff_id': 1, 'role_id': 2}
INFO:sqlalchemy.engine.base.Engine:COMMIT

为什么要删除?!

这很有趣,问题出在 staff 关系中的 Roles table 中。 uselist 应该是 True.