【发布时间】: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),其中user和role都是表格。
标签: node.js sequelize.js nested-queries