续集循环依赖 [英] Sequelize cyclic dependency

查看:17
本文介绍了续集循环依赖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的用户模型

'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 仍然抛出这个错误.为什么会这样?

Previously I had a cyclic dependency and it's now removed but sequelize still throws this error. Why is this happening?

如果我删除 User.hasMany(models.Media) 关联,错误将消失.但是为什么 Media 模型没有引用 User 模型时仍然会发生这种情况?

If I remove the User.hasMany(models.Media) association the error will disappear. But why is it still happening when the Media model has no reference to the User model?

推荐答案

考虑使用hasMany,如下:

Consider using hasMany as follows:

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

请注意,您不需要以下部分,但我认为它更清楚.

note that you don't need the following part but it makes it clearer in my opinion.

allowNull:true, defaultValue:null

这里解释得很好:http://docs.sequelizejs.com/zh/latest/api/associations/

这篇关于续集循环依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆