How to use LIKE with knex/postgres?

Asked

Viewed 121 times

0

I need to perform a consultation via knex, for a postgres bank, using the LIKE tag as below:

function getPessoas(nomeIncompleto){

return db('tab_pessoas').where('nomePessoa', 'like', '%nomeIncompleto%')

}

The query works, but the received variable in the function, is not recognized, or rather, 'nameNumber' is identified in its literal value and not from the received variable in the function.

Thanks in advance, hugs.

1 answer

1

Friends, I will answer myself to try to help someone with the same problem someday. For the above problem, I can indicate 2 solutions, there may be other:

In FIRST I solved using string interpolation and treating the function argument if it was not informed. To get better, I could exchange LIKE for ILIKE (not case sensitive)

function getPessoas(nomeIncompleto){
const n = nomeIncompleto ? nomeIncompleto : ''
return db('tab_pessoas').where('nomePessoa', 'like', `%${n}%`)
}

In the SECOND form, it replaces the LIKE with a postgres regex operator. I was also obliged to treat the function argument and used crase (interpolation).

function getPessoas(nomeIncompleto){
    const n = nomeIncompleto ? nomeIncompleto : ''
    return db('tab_pessoas').where('nomePessoa', '~*', `.*${n}`)
    }

If the procedure of answering a question of mine is wrong, forgive the moderators. I will make the necessary changes if requested.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.