簡體   English   中英

如何將 Sequelize model 及其關聯放在一個文件中?

[英]How do I put a Sequelize model and its assosications into one file?

我發現如果我不將所有關聯(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)

根據這篇文章,這可以通過將所有關聯放入一個文件來解決。

不過,我認為這不是一個好方法,因為

  1. 如果您想了解 model,您必須檢查 model 定義(以下示例中的models/user.ts )和關聯文件(類似於models/index.ts )。
  2. 如果您有許多具有關聯的模型,則關聯文件可能會非常大。

如何將 Sequelize model 及其關聯放入同一個文件中?

這就是我想要實現的目標。

// `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 };

任何建議將被認真考慮。

這就是我所做的。 我使用associate屬性在 model 聲明中聲明每個 model 關聯。 在您的情況下,例如:

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); 
  }
});

通過這種方式,我可以保持緊湊的索引,動態獲取和應用關聯,並在每個 model 中聲明關聯

我對幾年前提出的類似問題的回答:

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

假設該方法是合理的,它的優點是它不需要單獨的“設置所有關聯”邏輯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM