Search code examples
mysqlsqlsequelize.jssql-like

Like Statement is not working for me in sequelize


What are you doing?

/* Code for Pagination */
    let limit = 4;   // number of records per page
    let offset = 0;
    let countallCompanies = 1000; 
    let page = req.body.page;      // 1 by default page number
    let order_by = req.body.order_by;  // id by default
    let order_by_ASC_DESC = req.body.order_by_ASC_DESC; // ASC by default
    let pages = Math.ceil(countallCompanies.count / limit);
    offset = limit * (page - 1); 
    /* End code for Pagination */
[err, companies] = await to(Company.findAll({ 
        where: { company_name: { like: '%'+ req.body.q +'%' } },
        limit: limit,
        offset: offset,
        order: [[order_by, order_by_ASC_DESC]]        
    }));

What do you expect to happen?

I expect sequelize to generate this query:

SELECT * FROM `Companies` AS `Company` WHERE company_name LIKE '%aa%' ORDER BY `Company`.`id` ASC LIMIT 0, 4

What is actually happening?

Instead it generates this query:

SELECT * FROM `Companies` AS `Company` ORDER BY `Company`.`id` ASC LIMIT 0, 4

The WHERE condition is not added to my query even though the other clauses are like ORDER BY, LIMIT, etc. I have tried using both like and $like, but neither worked. If I add where: { id: 53 } then the WHERE clause does appear.


Solution

  • Add const Op = Sequelize.Op; at start of file.

    There are two ways to use like. $like: [Op.like].

    Also try with hard coded value to see if your data is fine.