Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the $in operator with SequelizeJS?

I'm trying to use the $in operator in SequelizeJS as you would in a MySQL statement:

SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);

In my case, I've joined three tables, but I don't believe that's related to the issue. I keep getting this error Error: Invalid value { '$in': ['12345','67890','15948'] } with the following code:

definedTable.findAll({
  include: [{
    model: definedTableTwo,
    where: {
      zip_code: {
        $in: ['12345','67890','15948']
      }
    },
    required: true,
    plain: true
  },
  {
    model: definedTableThree,
    required: true,
    plain: true
  }]
})

Can someone provide some insight on how to use the $in operator? The only examples I've seen are with integers within the array when searching Ids.

like image 589
SReca Avatar asked Apr 06 '18 20:04

SReca


People also ask

How do you use the operator in Sequelize?

You need to import the object from Sequelize to use it in your code: const { Sequelize, Op } = require("sequelize"); When you call the query methods from your model, you can use the Op object properties to create SQL queries with operators.

Where is $in Sequelize?

Sequelize where option accepts an object describing the WHERE clause to add to your generated SQL query. For a WHERE clause with a simple condition, you can add a single property to the where object. The property name will be the column name and the property value will be the value you use to filter the query.

How do I use raw query in Sequelize?

As there are often use cases in which it is just easier to execute raw / already prepared SQL queries, you can use the sequelize. query method. By default the function will return two arguments - a results array, and an object containing metadata (such as amount of affected rows, etc).


1 Answers

Just reading the docs here Sequelize WHERE

I'd try :

const Op = Sequelize.Op;
definedTable.findAll({
  include: [{
    model: definedTableTwo,
    where: {
      zip_code: {
        [Op.in]: ['12345','67890','15948']
          }
    },
    required: true,
    plain: true
  },
  {
    model: definedTableThree,
    required: true,
    plain: true
  }]
})

Does that help ?

like image 53
pierreaurelemartin Avatar answered Oct 22 '22 12:10

pierreaurelemartin