1. 再今兴多对多的关系设定的时候,我们会绑定中间表
中间表:
Users_roles = db.Table("users_roles", db.Model.metadata,
db.Column("user_id", db.Integer, db.ForeignKey("user.id"), primary_key=True),
db.Column("role_id", db.Integer, db.ForeignKey("role.id"), primary_key=True)
)
class User(db.Model):
__tablename__ = 'user'
id = db.Column(db.Integer, db.Sequence('user_id_seq'), primary_key=True)
user_id = db.Column(db.String(80), unique=True) # 员工编号
name = db.Column(db.String(80), nullable=False) # 员工姓名
# job_title = db.Column(db.String(80), default="engineer")
# mgr_title = db.Column(db.String(80), default="employee")
_password = db.Column(db.String(128), nullable=False) # 密码, BCRYPT
active = db.Column(db.Boolean(), default=False)
user_type = db.Column(db.String(80), default="user")
status = db.Column(db.String(80), default="deactivate")
department_id = db.Column(db.Integer, db.ForeignKey('department.id'))
dr = db.Column(db.Integer, default=0)
creator_id = db.Column(db.Integer, db.ForeignKey('user.id'))
creator = db.relationship("User", backref='created_by', remote_side=[id], foreign_keys=[creator_id])
created_at = db.Column(db.DateTime, default=datetime.now)
modifyuser_id = db.Column(db.Integer, db.ForeignKey('user.id'))
modifyuser = db.relationship("User", backref='modified_by', remote_side=[id], foreign_keys=[modifyuser_id])
modify_at = db.Column(db.DateTime)
roles = relationship("Role", secondary=Users_roles, backref="users")
# 再为secondary赋值的时候,不加引号赋的是类名,加引号赋得是表名
class Role(db.Model):
__tablename__ = 'role'
id = db.Column(db.Integer, Sequence('role_seq'), primary_key=True)
name = db.Column(db.String(80), nullable=False)
code = db.Column(db.String(80), nullable=False)
dr = db.Column(db.Integer, default=0)
creator_id = db.Column(db.Integer, db.ForeignKey('user.id'))
creator = db.relationship("User", foreign_keys=creator_id)
created_at = db.Column(db.DateTime, default=datetime.now)
modifyuser_id = db.Column(db.Integer, db.ForeignKey('user.id'))
modifyuser = db.relationship("User", foreign_keys=modifyuser_id)
modify_at = db.Column(db.DateTime)
privileges = relationship("Privilege", secondary=Roles_pris, backref="roles")