重新组合周期依赖关系

这是我的用户模型

'use strict'; var bcrypt = require('bcrypt'); module.exports = function(sequelize, DataTypes) { var User = sequelize.define('User', { email: { type: DataTypes.STRING, validate: { isEmail: true, notEmpty: true, notNull: false }, unique: true }, password: DataTypes.STRING, name: DataTypes.STRING, username: { type: DataTypes.STRING, unique: true }, admin: DataTypes.BOOLEAN, googleId: DataTypes.BOOLEAN }, { classMethods: { associate: function(models) { User.hasMany(models.Award); User.hasMany(models.Media); User.hasMany(models.Comment); User.hasMany(models.Like); User.hasMany(models.CheckIn); } } }); return User; }; 

这是我的媒体模式:

 'use strict'; module.exports = function(sequelize, DataTypes) { var Media = sequelize.define('Media', { type: DataTypes.ENUM('photo', 'video'), description: DataTypes.STRING, url: DataTypes.STRING, gps: DataTypes.GEOMETRY('POINT') }, { classMethods: { associate: function(models) { //Media.belongsTo(models.Event); //Media.belongsTo(models.User); Media.hasMany(models.Comment); Media.hasMany(models.Like); } } }); return Media; }; 

我得到这个错误:

 Unhandled rejection Error: Cyclic dependency found. Users is dependent of itself. Dependency chain: Awards -> Users -> Media => Users 

以前我有一个循环依赖,现在已经被删除,但是sequelize仍然会抛出这个错误。 为什么发生这种情况?

如果我删除User.hasMany(models.Media)关联错误将消失。 但是,为什么当媒体模型没有引用用户模型时,它仍然在发生?

考虑使用hasMany,如下所示:

 User.hasMany(models.Award, {as: 'ifYouWantAlias', constraints: false, allowNull:true, defaultValue:null}); 

注意,你不需要下面的部分,但是在我看来它更清晰。

 allowNull:true, defaultValue:null 

这里有很好的解释: http : //docs.sequelizejs.com/en/latest/api/associations/