Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize error when using "where" and "in" on a subarray

This is my model definition:

var Tag = sequelize.define('Tag', {
    name: Sequelize.STRING
});

var Event = sequelize.define('Event', {
    name: Sequelize.STRING,
});

Event.hasMany(Tag, {as: 'tags', through: 'event_tags', foreignKey: 'eventId'});
Tag.hasMany(Event, {as: 'events', through: 'event_tags', foreignKey: 'tagId'});

In words this is: there are events and tags. Events are tagged with many tags.

I'm trying to run this query:

Event
.findAndCountAll({
    include: [{model: Tag, as: 'tags'}],
    where: {'tags.id': {in: [1,2,3,4]}},
    order: order,
    limit: pageSize,
    offset: pageSize * (page - 1),
})
.success(function(result) {

    ...
});

But I'm getting this error:

   \node_modules\sequelize\lib\dialects\abstract\query-generator.js:1134
          var logicResult = Utils.getWhereLogic(logic, hash[key][logic]);
                                                                ^
   TypeError: Cannot read property 'in' of undefined

What am I doing wrong?

I've used before the "in" expression, for example here:

 Tag
 .find({
      where: {id: {in: [1,2,3,4]}}
 }).success(...)

And it worked just fine.

I've never used the in expression with a sub-array though, as in this case. So I don't know if thats the correct way to do it.

like image 897
sports Avatar asked Jul 23 '14 20:07

sports


3 Answers

No need "in" property, sequelize auto define this. Just set array.

Tag.findAll({     where: {         id: [1,2,3,4]     } }).then(...) 
like image 141
Enxtur Avatar answered Sep 23 '22 12:09

Enxtur


Updated example for Sequelize v5:

await Tag.findAll({   where: {     id: {       [Sequelize.Op.in]: [1, 2, 3, 4]     }   } }); 
like image 43
Brad Avatar answered Sep 23 '22 12:09

Brad


in property able to use at version 4.42

Tag.findAll({
    where: { id: {in: [1,2,3,4]} }
}).then(...)

And you can use notIn property for excluded values.

Tag.findAll({
    where: { id: {notIn: [1,2,3,4]} }
}).then(...)

http://docs.sequelizejs.com/manual/querying.html#operators

like image 40
samet Avatar answered Sep 22 '22 12:09

samet