Home  >  Q&A  >  body text

Creating dynamic 'andWhere' queries in TypeORM

<p>I'm trying to dynamically add a where clause to a query to filter an HTML table. I send an object to my API that contains filtered key-value pairs. It looks like this: </p> <pre class="brush:php;toolbar:false;">{Location: 'Seattle', Status: 'Active'}</pre> <p> Here's how I add each filter to the query: </p> <pre class="brush:php;toolbar:false;">const query = this.tableRepository.createQueryBuilder('myTable') .where('myTable.id = :id', {table_id}) varind=1 for (let key in myObj){ var varname = 'searchVal' String(ind) const searchVal = myObj[key] query.andWhere(`row_value.row_data->> '${key}' ILIKE :${varname}`, {varname: `%{searchVal%`}) }</pre> <p>The error I keep getting is the following error: ERROR [ExceptionsHandler] syntax error at or near ":" QueryFailedError: syntax error at or near ":". I'm sure the error is triggered by the {varname: '%{searchVal}%'} at the end, but I don't know how to change it. </p>
P粉334721359P粉334721359444 days ago474

reply all(1)I'll reply

  • P粉585541766

    P粉5855417662023-08-04 09:54:32

    It's okay, I figured it out - I was a little silly just now.

    I just need to change the last {varname: '%{searchVal}%'} to {[varname]: '%{searchVal}%'}.

    reply
    0
  • Cancelreply