【问题标题】:Use where clause with or condition in sequelize在 sequelize 中使用带或条件的 where 子句
【发布时间】:2020-08-03 01:07:37
【问题描述】:

我正在尝试在 sequelize 中使用或条件来表示查询,例如,

SELECT * FROM table WHERE title = "title" OR genre = "genre"

但是,这是我已经尝试过的

const checkTitle= await User.findOne({
        where: {
            $or: [
                { title: req.body.title },
                { genre: req.body.genre }
            ]
        }
    }).catch((err) => console.log(err.message));

但它一直给我一个错误,说无效值

Invalid value { title: 'title' }

请问sequelize如何正确使用OR条件?

【问题讨论】:

标签: mysql node.js sequelize.js


【解决方案1】:

您需要在代码中的标题和流派后面加上大括号。 代码应该是这样的:

const checkTitle= await User.findOne({
        where: {
            $or: [
                 title: {req.body.title },
                 genre: {req.body.genre }
            ]
        }
    }).catch((err) => console.log(err.message));

最新版本的sequelize修改了逻辑运算的语法。对于

续集 >= 4.12

const checkTitle= await User.findOne({
        where: {
            [Op.or]: [
                title: {req.body.title },
                description: {req.body.genre }
            ]
        }
    }).catch((err) => console.log(err.message));

【讨论】:

  • 是的,我用 [Op.or] 更改了 $or 并且成功了,谢谢!
猜你喜欢
  • 1970-01-01
  • 2018-10-06
  • 1970-01-01
  • 1970-01-01
  • 2021-10-28
  • 2014-11-07
  • 1970-01-01
  • 2018-06-30
  • 2014-02-07
相关资源
最近更新 更多