我在用户和角色之间具有关系N:M,也有一个名为UserRole的关联,其中存储了一些属性和两个外键:user_id
和role_id
。我的目标是将UserRole中的user_id
设置为主。
用户模型:
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define('User', {
// attributes
}, {
underscored: true,
hooks: {
beforeCreate: hashPassword,
beforeUpdate: hashPassword
}
})
User.associate = ({User, Role, UserRole}) => {
User.belongsToMany(Role, {
through: UserRole,
foreignKey: {
name: 'user_id',
allowNull: false
}
})
}
return User
}
角色模型:
module.exports = (sequelize, DataTypes) => {
const Role = sequelize.define('Role', {
// attributes
}, {
underscored: true
})
Role.associate = ({Role, User, UserRole}) => {
Role.belongsToMany(User, {
through: UserRole,
foreignKey: {
name: 'role_id',
allowNull: false
}
})
}
return Role
}
UserRole模型:
module.exports = (sequelize, DataTypes) => {
const UserRole = sequelize.define('UserRole', {
id: {
type: DataTypes.INTEGER,
allowNull: false,
autoIncrement: true,
unique: true,
primaryKey: true
},
// rest of attributes
}, {
underscored: true
})
return UserRole
}
如果如上所述进行设置,则会收到带有该代码的表UserRole:
CREATE TABLE IF NOT EXISTS "UserRoles" (
"id" SERIAL UNIQUE ,
"is_valid" BOOLEAN NOT NULL DEFAULT true,
"assigned_at" TIMESTAMP WITH TIME ZONE NOT NULL,
"revoked_at" TIMESTAMP WITH TIME ZONE,
"created_at" TIMESTAMP WITH TIME ZONE NOT NULL,
"updated_at" TIMESTAMP WITH TIME ZONE NOT NULL,
"user_id" INTEGER NOT NULL REFERENCES "Users" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
"role_id" INTEGER NOT NULL REFERENCES "Roles" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
UNIQUE ("user_id", "role_id"), PRIMARY KEY ("id")
);
但这不是我的目标。我尝试过在id
模型中删除UserRole
属性,并在User
模型中进行设置:
User.belongsToMany(Role, {
through: UserRole,
foreignKey: {
name: 'user_id',
allowNull: false,
primaryKey: true
}
})
但是后来我同时收到user_id
和role_id
作为PK。
是否有可能仅将一个外键设置为识别主键?或者,也许我没有正确理解N:M关联?
在此先感谢您的帮助。