2

In MySQL (And other dbs), you can do a where in query with multiple columns like below:

SELECT * FROM trains WHERE (name, location) IN (('train1', 'us'), ... ,('train2', 'us'));

I'm trying to do this with sequelize:

const selectTrains = [
    {name: 'train1', location: 'us'},
    {name: 'train1', location: 'eu'},
    {name: 'train2', location: 'us'},
];

let dbTrains = await Trains.findAll({ where: { [Op.in]: selectTrains} });

But I get the following error:

UnhandledPromiseRejectionWarning: Error: Invalid value {name: 'train1', location: 'us'}

The documentation didn't really cover this use case. Is this possible to do with the Op.in operator?

1
  • 1
    In most languages, this ends up just having to be a concatenated string, sadly Commented Apr 24, 2018 at 15:54

2 Answers 2

2

You can achieve the same thing with $or :

const selectTrains = [
    {name: 'train1', location: 'us'},
    {name: 'train1', location: 'eu'},
    {name: 'train2', location: 'us'},
];

Trains.findAll({ where: { $or : selectTrains} });
Sign up to request clarification or add additional context in comments.

2 Comments

I have noticed that I can do this, but it creates a massive OR statement, which is significantly less performant (By almost a factor of 3) than a WHERE IN statement.
@FrankerZ , then other option is to run raw query via sequelize.
0
Instead of **$or** use **Op.or**        
const selectTrains = [
            {name: 'train1', location: 'us'},
            {name: 'train1', location: 'eu'},
            {name: 'train2', location: 'us'},
];
        
// Trains.findAll({ where: { $or : selectTrains} });
 Trains.findAll({ where: { [**Op.or**] : selectTrains} });

2 Comments

Please add description to your question.
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

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.