2

I have a table in psql db like below.

[{
 name="ABC",
 email="xyz",
 animals=["cats","dogs","elephants","giraffes"]
},
{
 name="BCD",
 email="fgh",
 animals=["giraffes"]
}]
....

and an array that I'll get in the request like below

hasAnimals=["lion","cheetah","dog","cat"]

How do I use sequelize where clause to get the records of all the people in the above table who have at least 1 of the animals from the hasAnimals array.

For eg. the stated example should fetch me the user with name ABC as ABC has cats & dogs and so does the array that I got in the request

2 Answers 2

4

The solution turned out to be really simple.

const { Op } = require("sequelize");
let arr = []
for(let animal of animals) {
    arr.push({
        [Op.contains]: [animal],
    });
}

abc.findAll({
   where: {
      animals: {
         [Op.or]: arr
      }
   },    
})
Sign up to request clarification or add additional context in comments.

Comments

0

sql solution could be something like :

SELECT *
  FROM your_table
 WHERE your_json_column :: jsonb @? '$[*].animals[*] ? (@ <@ HasAnimals)'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.