How do you filter a query by multiple associations using sequelize.js?

2.9k views Asked by At

My project uses express.js and sequelize.js. I am trying to filter a query based on if it has one or more associations.

Here are my models:

const Tag = sequelizeConnection.define('tag', {
  title: {
    type: Sequelize.STRING,
    validate: {
      len: [1, 255]
    }
  },
  counter: {
    type: Sequelize.INTEGER,
    validate: {
      min: 0
    }
  }
})

const Post = sequelizeConnection.define('post', {
  category: {
    type: Sequelize.STRING,
    validate: {
      notEmpty: true
    }
  },
  title: {
    type: Sequelize.STRING,
    validate: {
      notEmpty: true,
      len: [1, 500]
    }
  },
  description: {
    type: Sequelize.TEXT,
    validate: {
      len: [0, 10000]
    }
  },
  images : {
    type: Sequelize.ARRAY(Sequelize.TEXT)

  },
  email: {
    type: Sequelize.STRING,
    validate: {
      notEmpty: true,
      isEmail: true
    }
  }
})

Tag.belongsToMany(Post, {through: 'postTag', foreignKey: 'tagId'});
Post.belongsToMany(Tag, {through: 'postTag', foreignKey: 'postId'});

Here is my query (it is hard coded for now for testing reasons)

router.route('/findPostsByTag')
.get((req, res) => {
  PostModel.findAll({
    include: [{model: TagModel, where: {title: ['cheap', 'cars']}}]
  })
  .then((data) => {
    res.send(data)
  })
  .catch((err) => {
    console.log(err)
    res.sendStatus(500)
  })
})

The query returns all posts that have the tag 'cheap', 'cars' and 'cheap' 'cars'.

I want it to return only the posts that have both the 'cheap' and 'cars' tags and exclude any post that only have one.

Any help would be appreciated! I haven't be able to find an answer in the docs or on forums for the past day!

1

There are 1 answers

0
jjbskir On

You want to use a $and operator in the query docs:

PostModel.findAll({
    include: [ {
        model: TagModel, 
        where: { $and: [ { title: 'cheap' }, { title: 'cars' } ] } 
    } ]
});