对nodejs和mysql的数据库关联进行序列化时出错

e37o9pze  于 2023-01-16  发布在  Node.js
关注(0)|答案(1)|浏览(135)
User.hasMany(Assignment, { as: 'assignments', foreignKey: 'tutorId' });
Assignment.belongsTo(User, { as: 'tutor', foreignKey: 'tutorId' });
Assignment.belongsToMany(User, {
  as: 'students',
  through: 'studentAssignment',
  foreignKey: 'assignmentId',
});
User.belongsToMany(Assignment, {
  as: 'assignments',
  through: 'studentAssignment',
  foreignKey: 'studentId',
});

Submission.belongsTo(User, { as: 'student', foreignKey: 'studentId' });
Submission.belongsTo(Assignment, {
  as: 'assignment',
  foreignKey: 'assignmentId',
});

throw new AssociationError( You have used the alias ${options.as} in two separate associations. Aliased associations must have unique aliases. ); ^
AssociationError [SequelizeAssociationError]: You have used the alias assignments in two separate associations. Aliased associations must have unique aliases. at new Association (C:\Users\User\OneDrive\Desktop\Toddle app\node_modules\sequelize\lib\associations\base.js:13:13) at new BelongsToMany (C:\Users\User\OneDrive\Desktop\Toddle app\node_modules\sequelize\lib\associations\belongs-to-many.js:33:5) at Function.belongsToMany (C:\Users\User\OneDrive\Desktop\Toddle app\node_modules\sequelize\lib\associations\mixin.js:43:25) at Object. (C:\Users\User\OneDrive\Desktop\Toddle app\toddleapp.js:76:8) at Module._compile (node:internal/modules/cjs/loader:1126:14) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1180:10) at Module.load (node:internal/modules/cjs/loader:1004:32) at Function.Module._load (node:internal/modules/cjs/loader:839:12) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) at node:internal/main/run_main_module:17:47
i am trying to do association then i got this error

iklwldmw

iklwldmw1#

您使用相同的assignments别名命名了两个关联:

User.hasMany(Assignment, { as: 'assignments', foreignKey: 'tutorId' });
User.belongsToMany(Assignment, {
  as: 'assignments',
  through: 'studentAssignment',
  foreignKey: 'studentId',
});

只需重命名其中一个:

User.hasMany(Assignment, { as: 'tutorAssignments', foreignKey: 'tutorId' });
User.belongsToMany(Assignment, {
  as: 'assignments',
  through: 'studentAssignment',
  foreignKey: 'studentId',
});

相关问题