【发布时间】: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,这可以通过将所有关联放在一个文件中来解决。
不过,我认为这不是一个好方法,因为
- 如果您想了解模型,您必须检查模型定义(以下示例中的
models/user.ts)和关联文件(类似于models/index.ts)。 - 如果您有许多具有关联的模型,则关联文件可能会非常大。
如何将 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