【问题标题】:How to write nested queries using sequelize in nodejs如何在nodejs中使用sequelize编写嵌套查询
【发布时间】:2022-02-01 20:58:53
【问题描述】:

我正在尝试使用此查询的 sequelize 编写嵌套查询。


const userIdPriorityLevel = await db.sequelize.query(
            `select "p_level" from roles  where id=(select "roleId" from users where id='${userId}');`
            , { raw: true });

上面的查询是这样工作的

用户表

id   roleId
1     2
2     3

角色表

id   p_level
2     4324
3     3423

请帮助如何做到这一点。

更新:


        const userIdPriorityLevel = await db.Role.findAll({
            attributes: ['p_level'],
            include: [{
                model: db.User,
                required: true,
                attributes: [],
                where: {
                    id: userId
                }
            }
            ]
        })

        console.log("userid   ", userIdPriorityLevel)

当我打印上面的查询时,它给了我这个输出

userid    [
  role {
    dataValues: { p_level: 700 },
    _previousDataValues: { p_level: 700 },
    _changed: Set(0) {},
    _options: {
      isNewRecord: false,
      _schema: null,
      _schemaDelimiter: '',
      include: [Array],
      includeNames: [Array],
      includeMap: [Object],
      includeValidated: true,
      attributes: [Array],
      raw: true
    },
    isNewRecord: false
  }
]

我只想从上面的输出中提取这个p_level: 700 值。尝试这样的事情

  const userPriorityLevel = userIdPriorityLevel[0][0]['p_level']

但它不起作用。

【问题讨论】:

  • 你到底想要什么?将这个普通的 SQL 查询重写为 Sequelize 查询?或者只是以某种方式纠正它?
  • 将这个普通的 SQL 查询重写为 Sequelize one
  • 您是否已经定义了 Sequelize 模型和关联?
  • 是的,我这样做了User.belongsTo(Role),其中userrole 都是表格。

标签: node.js sequelize.js nested-queries


【解决方案1】:

考虑到您也有 Role.hasMany(User) 关联,您可以尝试以下操作:

const roles = await Roles.findAll({
  attributes: ['p_level'],
  include: [{
    model: User,
    required: true,
    attributes: [],
    where: {
      id: userId
    }
  }
  ]
})

更新:为每个模型实例从 Sequelize 查询调用 get({ plain: true }) 获取普通对象:

const plainRoles = roles.map(x => x.get({ plain: true }))

【讨论】:

  • 它有效,谢谢。但是当我想从其输出中获取 p_level 值时,请检查我更新的问题。
  • 查看更新的答案
猜你喜欢
  • 2020-02-21
  • 1970-01-01
  • 1970-01-01
  • 2018-02-28
  • 1970-01-01
  • 1970-01-01
  • 2018-03-13
  • 2017-06-10
  • 2020-12-02
相关资源
最近更新 更多