首页 > 解决方案 > 续集急切负载问题:子级未与父级关联

问题描述

我有以下包含声明:

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

我有以下数据结构:OrganizationUsers:

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 和 organizationId 一切正常,但如果 OrganisationUsers 表中缺少关联,则会收到以下错误:

SequelizeEagerLoadingError: roles is not associated to organisation_users!

我不知道如何处理这个错误,我已经阅读了包括 required: false 声明,如上你可以看到我已经尝试过。

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

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

比一切都好。

如果您有任何想法、建议、建议等...请告诉我。

问候,埃米尔

标签: sequelize.jsfeathers-sequelize

解决方案


推荐阅读