在sequelize中,如何查询与'through'相关的模型

问题描述 投票:0回答:1

我是Sequelize的新手,需要帮助来创建一个在两个表之间进行查询的方法。我给了三个名为“user”,“project”和“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'
    }
  });

提前致谢。

associations sequelize.js
1个回答
0
投票

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

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

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;

});
© www.soinside.com 2019 - 2024. All rights reserved.