[英]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)
根據這篇文章,這可以通過將所有關聯放入一個文件來解決。
不過,我認為這不是一個好方法,因為
models/user.ts
)和關聯文件(類似於models/index.ts
)。如何將 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 中聲明關聯
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.