Sequelize紧急加载问题:子级与父级不相关

时间:2018-08-28 13:59:01

标签: sequelize.js feathers-sequelize

我有以下包含声明:

context.params.sequelize = {
    raw: false,
    include: [{
      model: organisationUsers,
      required: false,
      include: [{
        required: false,
        model: roles,
        where: roleId ? { roleId } : undefined,
      }],
    }],
}

我具有以下数据结构: 机构用户:

const organisationUsers = sequelizeClient.define('organisation_users', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    roleId: {
      type: DataTypes.INTEGER,
      allowNull: true,
    },
    organisationId: {
      type: DataTypes.INTEGER,
      allowNull: true,
    },
    userId: {
      type: DataTypes.INTEGER,
      allowNull: true,
    },
  }, {
      hooks: {
        beforeCount(options) {
          options.raw = true;
        },
      }
    });

  // eslint-disable-next-line no-unused-vars
  organisationUsers.associate = (models) => {
    // Define associations here
    // See http://docs.sequelizejs.com/en/latest/docs/associations/
    organisationUsers.belongsTo(models.organisations, { foreignKey: 'organisationId' });
    organisationUsers.belongsTo(models.roles, { foreignKey: 'roleId' });
    organisationUsers.belongsTo(models.users, { foreignKey: 'userId' });
  };

角色:

const roles = sequelizeClient.define('roles', {
    name: {
      type: DataTypes.STRING,
      allowNull: false
    }
  }, {
      hooks: {
        beforeCount(options) {
          options.raw = true;
        }
      },
    });

  // eslint-disable-next-line no-unused-vars
  roles.associate = (models) => {
    // Define associations here
    // See http://docs.sequelizejs.com/en/latest/docs/associations/
    roles.belongsToMany(models.permissions, { through: 'role_permissions' });
    roles.hasMany(organisationUsers(app), { foreignKey: 'roleId' });
  };

和用户:

const users = sequelizeClient.define('users', {
    email: {
      type: DataTypes.STRING,
      allowNull: false,
      unique: true,
      validate: {
        isEmail: true
      }
    },
    password: {
      type: DataTypes.STRING,
      allowNull: false
    },
  }, {
      hooks: {
        beforeCount(options) {
          options.raw = true;
        }
      }
    });

  // eslint-disable-next-line no-unused-vars
  users.associate = (models) => {
    // Define associations here
    // See http://docs.sequelizejs.com/en/latest/docs/associations/
    users.hasMany(organisationUsers(app), { foreignKey: 'userId' });
  };

如果OrganisationUsers表中包含一个roleId,userId和organisationId,则一切正常,但是如果OrganisationUsers表中缺少关联,则会出现以下错误:

SequelizeEagerLoadingError: roles is not associated to organisation_users!

我不确定如何处理此错误,我已经阅读过有关包含required:false语句的信息,如上所述,您可以看到我已经尝试过了。

我不确定问题是否是由于嵌套的包含?如果我删除嵌套的include使其看起来像这样:

context.params.sequelize = {
        raw: false,
        include: [{
          model: organisationUsers,
        }],
    }

比一切正常。

如果您有任何想法,建议,建议等...请让我知道。

关于, 埃米尔

0 个答案:

没有答案