在 Sequelize 我使用 findByPk 但我还需要通过另一个条件
const options = {
where: { role: 'admin' },
};
return models.User.findByPk(id, options)
.then((user) => {...
但即使角色不是管理员,此查询也会重新调整所有用户。我检查了生成的 SQL,我看到
SELECT * from User WHERE id = 1 但我没有看到 AND 角色 = 'admin'。
如何使用 findByPk 并传递另一个条件?
谢谢你
最佳答案
您必须改用 findOne
,并将主键作为 where
对象中的字段传递:
return models.User.findOne({
where: {
id: id,
role: 'admin',
},
})
Sequelize 文档可能有点困惑……但是,
options
中的 findByPk
参数与 findOne
中的参数取不同的值。如果您仔细查看 documentation for findByPk ,您会在底部看到一条注释,内容为:See: Model.findAll for a full explanation of options, Note that options.where is not supported.
关于sequelize.js - 在 Sequelize 中使用 findByPk 和 WHERE 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59111392/