在续集中,如何查询与'through'关联的模型



我是Sequelize的新手,需要帮助创建一个在两个表之间查询的方法。我给出了三个模型,分别命名为">user"、">项目和">user_project"。

user_project存储用户和项目之间的关系。它使用来自其他表的两个外键(user_id和project_id)。此外,user_project有一个名为"role"的字段,用于指定用户在项目中的角色。我正试图找出一种基于用户"电子邮件"提取用户角色的方法。注意,用户电子邮件存储在用户表中。

它们之间的关联如下:

models.project.belongsToMany(models.user, {
through: models.user_project,
foreignKey: {
name: 'projectId',
field: 'project_id'
}
});
models.user.belongsToMany(models.project, {
through: models.user_project,
foreignKey: {
name: 'userId',
field: 'user_id'
}
});

提前谢谢。

知道这已经很晚了,但希望将来会有其他人-

使用原始查询,然后将角色字符串转换为数组-

User.findOne({
where: {email},
attributes: [
'id', 'email',
[Sequelize.literal("(SELECT GROUP_CONCAT(roles) FROM user_project UP WHERE UP.user_id=user.id )"), "roles"],
]
}).then( (user) => {
if(!user)
return null;
user = JSON.parse(JSON.stringify(user));
if(!user.roles)
user.roles = [];
else
user.roles = user.roles.split(",");
return user;
});

在不使用Raw的情况下获取角色-

User.findOne({
where: {email},
attributes: [
'id', 'email'
],
include: [
{
model: Db.user_project,
required: false,
attributes: ["user_id", "roles"]
}
]
}).then( (user) => {
if(!user)
return null;
user = JSON.parse(JSON.stringify(user));
if(!user.roles)
user.roles = [];
else
user.roles = user.roles.map(r => r.roles);
return user;
});

最新更新