您好,表格Users
与Groups
到UsersGroups
有多对多的关系。 UsersGroups
具有UsersGroupsRoles
的FK:
用户:
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
子句,但是,在中间表中包含一对多关联的正确方法是什么?
谢谢!
答案 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)
}