简体   繁体   中英

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. Now I want to use sequelize's built-in "where" clause to filter by values on this new field.

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'". I've also tried:

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

Which works with the order property from sequelize, but not here.

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. For some reason Sequelize.having is not on the DOCS/API, and I already opened an issue at the git repo.

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}}
 })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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