How do I escape % in Knex where like query?

后端 未结 6 1624
挽巷
挽巷 2021-01-18 00:09

I\'m using knex to generate my SQL queries. In knex documentation, it shows this

knex(\'users\').where(\'columnName\', \'like\', \'         


        
6条回答
  •  长情又很酷
    2021-01-18 00:50

    Knex doesn't have an equivalent to the ESCAPE keyword [1], so you have to do a raw query like this, which will search for users with name === "%foo%":

    knex.raw('select * from users where name like ? escape \', ['\%foo\%'])
    

    And this, with an unescaped wildcard at the beginning of the search term, will search for users with name ending in "%foo%":

    knex.raw('select * from users where name like ? escape \', ['%\%foo\%'])
    

    [1] Closed feature request: https://github.com/knex/knex/issues/648

提交回复
热议问题