Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize - How to search multiple columns?

I have a database of articles with several columns and would like to be able to search both title and description.

Currently, I have:

Article.findAll({
  where: {
    title: { like: '%' + searchQuery + '%' }
  }
});

How can I also search the description as well?

I've read through the sequelize documentation, even in the Complex filtering / OR / NOT queries section, but the examples only seem to explain searching in one column.

like image 868
waffl Avatar asked Dec 13 '15 20:12

waffl


2 Answers

Sequelize >= 4.12

const Op = Sequelize.Op;
Article.findAll({
  where: {
    title: { [Op.like]: '%' + searchQuery + '%' },
    description: { [Op.like]: '%' + searchQuery2 + '%' }
  }
});

Sequelize < 4.12

Article.findAll({
  where: {
    title: { like: '%' + searchQuery + '%' },
    description: { like: '%' + searchQuery2 + '%' }
  }
});

The above will make sure title includes searchQuery and description includes searchQuery2. If you however would like to get results back when an Article includes one of the two, the following query should work:

Sequelize >= 4.12

const Op = Sequelize.Op;
Article.findAll({
  where: {
    [Op.or]: [
     title: { [Op.like]: '%' + searchQuery + '%' },
     description: { [Op.like]: '%' + searchQuery2 + '%' }
    ]
  }
});

Sequelize < 4.12

Article.findAll({
  where: {
    $or: [
     title: { like: '%' + searchQuery + '%' },
     description: { like: '%' + searchQuery2 + '%' }
    ]
  }
});
like image 75
leroydev Avatar answered Nov 13 '22 06:11

leroydev


Sequelize >= 4.12

Article.findAll({
 where = {
  [Op.or]: [
    { name: { [Op.like]: `%${req.query.query_string}%` } },
    { description: { [Op.like]: `%${req.query.query_string}%` } }
  ]
}
});

just fyi: mysql doesn't supports iLike ;)

like image 6
A_J Avatar answered Nov 13 '22 06:11

A_J