简体   繁体   English

Sequelize:在 where 子句中使用在 sequelize.literal 中创建的字段

[英]Sequelize: use field created in sequelize.literal in where clause

I am using sequelize.literal function to create an aggragated field, which was not achievable in other ways.我正在使用 sequelize.literal function 创建一个聚合字段,这是其他方式无法实现的。 Now I want to use sequelize's built-in "where" clause to filter by values on this new field.现在我想使用 sequelize 的内置“where”子句来过滤这个新字段上的值。

DB_A.findAll({
attributes: {
  include: [
    [
      sequelize.literal(
        `(SELECT COUNT (*) FROM DB_B as DB_B WHERE DB_B.a_id = DB_A.id)`
      ),
      "b_count",
    ],
         
  ]} 
where:{ b_count:{[Op.gte]:10}}
 })

When I do this, I get "Unknown column 'DB_A.b_count' in 'where clause'".当我这样做时,我得到“'where 子句'中的未知列'DB_A.b_count'”。 I've also tried:我也试过:

where:{[sequelize.literal("b_count")]:...}

Which works with the order property from sequelize, but not here.它适用于 sequelize 的 order 属性,但不适用于此处。

Any ideas?有任何想法吗?

Ok, I figured it out.好的,我想通了。 You need to use "having" instead of "where", as it would be the way to do with regular MySQL.您需要使用“have”而不是“where”,因为这将是使用常规 MySQL 的方式。 For some reason Sequelize.having is not on the DOCS/API, and I already opened an issue at the git repo.由于某种原因, Sequelize.having不在 DOCS/API 上,我已经在 git 存储库中打开了一个问题。

The above code would then be:上面的代码将是:

DB_A.findAll({
attributes: {
  include: [
    [
      sequelize.literal(
        `(SELECT COUNT (*) FROM DB_B as DB_B WHERE DB_B.a_id = DB_A.id)`
      ),
      "b_count",
    ],
         
  ]} 
having:{ ["b_count"]:{[Op.gte]:10}}
 })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM