在quelize node.js中使用const而不是来自数据库的值

发布于 2025-02-12 11:19:31 字数 844 浏览 1 评论 0原文

我正在研究一个具有一些用户和角色的项目。我想在用户和角色上添加关联(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 技术交流群。

扫码二维码加入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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文