felixfbecker / node-sql-template-strings

ES6 tagged template strings for prepared SQL statements 📋
ISC License
610 stars 40 forks source link

How do I write conditional queries? #57

Closed matbz closed 7 years ago

matbz commented 7 years ago

Unfortunately, the code below doesn't work. How can I make this logic work? I also need this because sometimes I need a join or not based on a parameter passed to the model.

I don't think an append would work in this case as there is always a where condition?

Thanks!


      let where = `budget_id = ${budgetid}`;
      if (filter.accountid) {
        where += ` and a.id = ${accountid}`;
      }

      const query = SQL`
      select
        t.id,
        a.id as account_id,
        a.name as account_name,
        c.id as category_id,
        c.name as category_name,
        t.amount,
        t.turnover_date,
        t.note
      from account as a
      inner join turnover as t
      on t.account_id = a.id
      inner join category as c
      on t.category_id = c.id
      where
        ${where}
      order by t.turnover_date desc
      `;
felixfbecker commented 7 years ago

You are not using the SQL template string tag on the first two template strings. Please see https://github.com/felixfbecker/node-sql-template-strings#building-complex-queries-with-append how to compose queries:

      let where = SQL`budget_id = ${budgetid}`;
      if (filter.accountid) {
        where.append(SQL` and a.id = ${accountid}`);
      }

      const query = SQL`
      select
        t.id,
        a.id as account_id,
        a.name as account_name,
        c.id as category_id,
        c.name as category_name,
        t.amount,
        t.turnover_date,
        t.note
      from account as a
      inner join turnover as t
      on t.account_id = a.id
      inner join category as c
      on t.category_id = c.id
      where `.append(where).append(SQL`
      order by t.turnover_date desc
      `;

should work.