Search code examples
typeorm

Column name as variable in typeorm querybuilder


This is my original code which does not work.

this.createQueryBuilder().where(
      'LOWER(:column) LIKE LOWER(:name)',
      { column: 'itemName', name: `%${options.name}%` }
    );
{ "total": 0, "results": [] }

I get no results from the above query but when I explicitly place the column name in the query like this, it works:

this.createQueryBuilder().where(
      'LOWER(itemName) LIKE LOWER(:name)',
      { name: `%${options.name}%` }
    );
{"total":9, "results": [<RESULTS GOES HERE>] }

Is it possible to use a variable in the column name for typeorm?


Solution

  • Yes, but with some drawbacks.

    Build your query as a string and parse inside the Where function

    const query = `{ "${field}": ${value} }`
    this.createQueryBuilder.where( JSON.parse(query) )
    

    If you want to do more complex, you should write as normal, but in string format.