【问题标题】:How do I put a Sequelize model and its assosications into one file?如何将 Sequelize 模型及其关联放入一个文件中?
【发布时间】:2021-06-08 00:33:16
【问题描述】:

我发现如果我不将所有关联(hasMany 等)放入一个文件中,则会出现以下错误。

   throw new Error(`${this.name}.belongsToMany called with something that's not a subclass of Sequelize.Model`);
   ^
Error: users.belongsToMany called with something that's not a subclass of Sequelize.Model
  at Function.belongsToMany (C:\app\node_modules\sequelize\lib\associations\mixin.js:49:13)
  at Object.<anonymous> (C:\app\models\/user.ts:51:6)

根据this post,这可以通过将所有关联放在一个文件中来解决。

不过,我认为这不是一个好方法,因为

  1. 如果您想了解模型,您必须检查模型定义(以下示例中的models/user.ts)和关联文件(类似于models/index.ts)。
  2. 如果您有许多具有关联的模型,则关联文件可能会非常大。

如何将 Sequelize 模型及其关联放入同一个文件中?

这就是我想要实现的目标。

// `models/user.ts`
import { Role } from './role';

const User = sequelizeInstance.define<UserInstance>(
  'users',  {/* fields */},
);

User.belongsToMany(Role, {
  through: 'user_roles',
  foreignKey: 'userId',
  otherKey: 'roleId',
});

export { User };
// `model/role.ts`.
import { User } from './user';

const Role = sequelizeInstance.define<RoleInstance>(
  'roles', {/* fields */}
);

Role.belongsToMany(User, {
  through: 'user_roles',
  foreignKey: 'userId',
  otherKey: 'roleId',
});

export { Role };

我们将不胜感激。

【问题讨论】:

    标签: node.js sequelize.js


    【解决方案1】:

    这就是我所做的。 我在模型声明中声明每个模型关联,使用associate 属性。在你的情况下是这样的:

    const Role = sequelizeInstance.define<RoleInstance>(
      'roles', {/* fields */}
    );
    Role.associate  = function (models) {
       Role.belongsToMany(models.users, {
         through: 'user_roles',
         foreignKey: 'userId',
         otherKey: 'roleId',
       });
    });
    

    然后在我的索引文件中,我写了几行来从模型声明中获取所有关联并应用它们:

    db.roles = // assign your Role model
    db.users = // assign your User model
    
    // setup table associations
    Object.keys(db).forEach(function (modelName) {
      if ('associate' in db[modelName]) {
        // call the associate function and pass reference to all other models
        db[modelName].associate(db); 
      }
    });
    

    通过这种方式,我可以保持一个紧凑的索引,动态获取和应用关联,并在每个模型中声明关联

    【讨论】:

    • 非常感谢您的建议!这行得通。你能告诉我为什么你把models作为Role.associate = function (models)...的参数吗? models 没有在回调中使用,我认为
    • 好点,我更新了我的答案; models 参数包含对index 文件中定义的所有其他模型的引用;所以在您的模型文件中,您可以避免导入关联的模型,因为这将作为 associate 函数的参数传递
    【解决方案2】:

    我对几年前提出的类似问题的回答:

    https://stackoverflow.com/a/67875061/11558646

    假设该方法是合理的,它的优点是它不需要单独的“设置所有关联”逻辑。

    【讨论】:

      猜你喜欢
      • 2016-11-02
      • 1970-01-01
      • 1970-01-01
      • 2021-08-02
      • 1970-01-01
      • 2017-03-30
      • 2017-11-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多