How to implement search feature using SequelizeJS?

后端 未结 2 409
余生分开走
余生分开走 2021-01-18 05:23

I have a Ticket model and a Comment model. The Ticket has a hasMany relationship to Comment model. I want to search tickets by a keyword. The keyword will be matched againts

相关标签:
2条回答
  • 2021-01-18 05:35
    const { Op } = require("sequelize");
    
    var options = {
      where: {
        [Op.or]: [
          { 'subject': { [Op.like]: '%' + query + '%' } },
          { '$Comment.body$': { [Op.like]: '%' + query + '%' } }
        ]
      },
      include: [{ model: Comment }]
    };
    

    Op.iLike can be used for case-insensitive search.

    0 讨论(0)
  • 2021-01-18 05:40

    Probably a bit too late for you, but for anyone else; #3095 was updated with a bit of a solution:

    var options = {
      where: {
        $or: [
          { 'subject': { like: '%' + query + '%' } },
          { '$Comment.body$': { like: '%' + query + '%' } }
        ]
      },
      include: [{ model: Comment }]
    };
    

    The trick is in those dollar signs, though there are still problems with this solution when limit is set or when querying with findAndCountAll().

    0 讨论(0)
提交回复
热议问题