在quelize node.js中使用const而不是来自数据库的值
我正在研究一个具有一些用户和角色的项目。我想在用户和角色上添加关联(allatystomany)。我正在使用MySQL数据库,并且用户存储在用户表中。目前,我还在数据库中存储角色,但我希望将角色存储在文件中而不是数据库中。有什么方法可以使用数据库中的const而不是表。
index.js file:
...
db.user = require("./user.model.js")(sequelize, Sequelize);
db.role = require("./role.model.js")(sequelize, Sequelize);
db.role.belongsToMany(db.user, {
through: "user_roles",
foreignKey: "roleId",
otherKey: "userId"
});
db.user.belongsToMany(db.role, {
through: "user_roles",
foreignKey: "userId",
otherKey: "roleId"
});
角色.model.js文件
module.exports = (sequelize, Sequelize) => {
const Role = sequelize.define("role", {
id: {
type: Sequelize.INTEGER,
primaryKey: true
},
name: {
type: Sequelize.STRING
}
});
return Role;
};
I'm working on a project that has some users and roles. I want to add association (belongsToMany) on users and roles. I'm using MySQL database and users are stored in users table. Currently i'm storing roles in database as well but i want roles to be stored in a file instead of database. Is there a way i could use a const instead of table from database.
index.js file:
...
db.user = require("./user.model.js")(sequelize, Sequelize);
db.role = require("./role.model.js")(sequelize, Sequelize);
db.role.belongsToMany(db.user, {
through: "user_roles",
foreignKey: "roleId",
otherKey: "userId"
});
db.user.belongsToMany(db.role, {
through: "user_roles",
foreignKey: "userId",
otherKey: "roleId"
});
role.model.js file
module.exports = (sequelize, Sequelize) => {
const Role = sequelize.define("role", {
id: {
type: Sequelize.INTEGER,
primaryKey: true
},
name: {
type: Sequelize.STRING
}
});
return Role;
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以做的一件事是消除角色表,只需在用户表中创建一个带有andersto()关联的userrole表即可。 (并通过使用Hasmany())
将用户与userrole中的“名称”列具有 enum datatype ,并让模型绘制该枚举中可用的值,从文件系统。 (或者,您可以将值对枚举进行用力编码,这将是您更新可能的角色名称的“文件”)
我不确定这是什么问题要解决的。这似乎会导致整体绩效的下降,尽管这将消除对与之沮丧的许多关系的需求。
One thing that you could do is eliminate the Role table, and just create a UserRole table with a belongsTo() association to the User table. (And associate User to it by using hasMany())
You could then make the "name" column in UserRole have the ENUM datatype, and have the model draw the values available in that ENUM from reading the file in the file system. (Alternately, you can hard-code the values into the ENUM and that would be the "file" where you're updating possible role names)
I'm not totally sure what problem this is looking to solve, though. This seems like it would lead to a decrease in performance overall, though it WOULD eliminate the need for a Many-to-Many relationship that can be frustrating to work with.