在Sequelize查询中使用带有功能的WHERE

时间:2019-05-14 02:00:30

标签: sqlite sequelize.js

我正在尝试在Sequelize查询中使用函数JSON_ARRAY_LENGTH()

MyModel.query({
  where: sequelize.where(
    sequelize.fn('JSON_ARRAY_LENGTH', sequelize.col('cues')),
    0
  )
});

这似乎不起作用。它将生成错误的查询:

SELECT id, title, /* etc. etc. */
FROM MyModel
WHERE
  `MyModel`.`attribute` = JSON_ARRAY_LENGTH(`cues)` AND
  `MyModel`.`comparator` = '=' AND
  `MyModel`.`logic` = 0;

attributecomparatorlogic这些东西是什么?如何关闭它?

documentation似乎支持我在做什么。例如:

Post.findAll({
  where: sequelize.where(sequelize.fn('char_length', sequelize.col('status')), 6)
});
// SELECT * FROM post WHERE char_length(status) = 6;

任何想法都会受到赞赏。谢谢!

1 个答案:

答案 0 :(得分:0)

似乎我偶然发现了一个错误:

https://github.com/sequelize/sequelize/issues/6440

此问题已在较新的版本中修复:

https://github.com/sequelize/sequelize/pull/9730/commits/3b2972db2c494c8a4118a7e6c16aad0fc2e0eebe

目前的解决方法是用AND包裹我的查询:

MyModel.query({
  where: {
    [sequelize.Op.and]: sequelize.where(
      sequelize.fn('JSON_ARRAY_LENGTH', sequelize.col('cues')),
      0
    )
  }
});