中间表中的多对多关系和一对多关系

时间:2019-03-15 07:09:27

标签: javascript sequelize.js

您好,表格UsersGroupsUsersGroups有多对多的关系。 UsersGroups具有UsersGroupsRoles的FK:

enter image description here

用户:

module.exports = (sequelize, Sequelize) => {
    const Users = sequelize.define(
        'Users',
        {
            id: {
                type: Sequelize.UUID,
                defaultValue: Sequelize.UUIDV4,
                primaryKey: true,
            },

            name: {
                type: Sequelize.STRING,
            },
        },
        {}
    );
    Users.associate = function(models) {
        Users.belongsToMany(models.Groups, { through: models.UsersGroups });
    };

    return Users;
};

组:

module.exports = (sequelize, Sequelize) => {
    const Groups = sequelize.define(
        'Groups',
        {
            id: {
                type: Sequelize.INTEGER,
                autoIncrement: true,
                primaryKey: true,
                allowNull: false,
            },

            name: {
                type: Sequelize.STRING,
            },
        },
        {}
    );

    Groups.associate = function(models) {
        Groups.belongsToMany(models.Users, { through: models.UsersGroups });
    };

    return Groups;
};

UsersGroups:

module.exports = (sequelize, Sequelize) => {
    const UsersGroups = sequelize.define(
        'UsersGroups',
        {
            order: {
                allowNull: true,
                type: Sequelize.INTEGER,
                defaultValue: 10000,
            },
        },
        {}
    );
    UsersGroups.associate = function(models) {
        UsersGroups.belongsTo(models.UsersGroupsRoles, { as: 'UsersGroupsRoles', onDelete: 'CASCADE' });
    };

    return UsersGroups;
};

UsersGroupsRoles:

module.exports = (sequelize, Sequelize) => {
    const UsersGroupsRoles = sequelize.define(
        'UsersGroupsRoles',
        {
            id: {
                type: Sequelize.INTEGER,
                autoIncrement: true,
                primaryKey: true,
                allowNull: false,
            },

            role: {
                type: Sequelize.STRING,
            },
        },
        {}
    );

    UsersGroupsRoles.associate = function(models) {
        UsersGroupsRoles.hasMany(models.UsersGroups, { as: 'UsersGroupsRoles', onDelete: 'CASCADE' });
    };

    return UsersGroupsRoles;
};

现在,我要查询用户和用户组,并获取UsersGroupsRoles

models.Groups.findAll({
    attributes: {
        exclude: ['createdAt', 'updatedAt'],
    },
    include: [
        {
            model: models.Users,
            attributes: {
                exclude: ['createdAt', 'updatedAt', 'email', 'password'],
            },
            through: {
                include: [
                    {
                        model: models.UsersGroupsRoles,
                        as: 'UsersGroupsRoles',
                    },
                ],
            },
        },
    ],
})

但是查询失败,并显示TypeError: Cannot read property 'indexOf' of undefined。我想这是因为include中的through子句,但是,在中间表中包含一对多关联的正确方法是什么?

谢谢!

1 个答案:

答案 0 :(得分:0)

尝试一下吗?

try {
    let groups = await models.Groups.findAll({
      attributes: {
          exclude: ['id','createdAt', 'updatedAt'],
      }
    })

    const userGroupsPromises = groups.map(group => {
      return models.UsersGroups.findAll({
        where: {
          groupId: group.id
        },
        include: [{
          model: models.User,
          attributes: {
            exclude: ['createdAt', 'updatedAt', 'email', 'password'],
        }
        }, {
          model: models.UsersGroupsRoles,
        }]
      })
    })

    const userGroupsPromiseResult = await Promise.all(userGroupsPromises)

    groups = groups.map((group, index) => {
      const _group = group.get()
      _group.UserGroups = userGroupsPromiseResult[index]

      return _group
    })

    console.log(groups)
  } catch (err) {
    console.log(err)
  }