项目场景:
项目开发中用到一个比较经典的用户权限库表设计,关系如下图所示:

t_user是用户表,t_role是角色表,t_user_role是两者之间的联结表,用户表和角色表是多对多的关系,通过t_user_role表的user_id和role_id进行外键关联。
各表用sequelize的Model定义如下:
1)用户表:
const Model = sequelize.define(
'User',
{
id: {
type: DataTypes.CHAR(21),
allowNull: false,
primaryKey: true,
comment: '主键',
},
mobile: {
type: DataTypes.STRING(20),
allowNull: false,
comment: '手机号码',
unique: 'ukey',
},
name: {
type: DataTypes.STRING(64),
allowNull: true,
comment: '姓名',
},
job: {
type: DataTypes.STRING(64),
allowNull: true,
comment: '职务/职称',
},
admin: {
type: DataTypes.BOOLEAN,
allowNull: true,
defaultValue: 0,
comment: '是否系统管理员(0-否 1-是)',
},
status: {
type: DataTypes.BOOLEAN,
allowNull: true,
defaultValue: 1,
comment: '状态(0-冻结,1-正常)',
},
remark: {
type: DataTypes.STRING(255),
allowNull: true,
comment: '备注',
},
lastLoginDate: {
type: DataTypes.DATE,
allowNull: true,
comment: '最后一次登录时间',
field: 'last_login_date',

在项目开发中遇到Sequelize针对多对多关系的联结表查询时出现'Unknown column 'UserId' in 'field list''错误。问题源于在定义User模型与Role模型的belongsToMany关联时,未正确设置foreignKey和otherKey。解决方案是明确指定这两个属性,以避免Sequelize自动生成错误的SQL查询语句。
最低0.47元/天 解锁文章
2万+

被折叠的 条评论
为什么被折叠?



