0

I'm a PHP Developer and for a new project I decided to use a node.js backend. So I'm quite new to that.

I'm using knex.js to handle my database connection and manipulate the data. F.ex I have the following query:

let gastronomies = await knex
  .from('user')
  .innerJoin('profile', 'user.id', 'profile.user_id')
  .where('user.status', 1);

If the client passes an additional variable to the function it should be used as another query param

if(args.lat) {
    gastronomies = await knex
    .from('user')
    .innerJoin('profile', 'user.id', 'profile.user_id')
    .where('user.status', 1)
    .where('lat', 'like', args.lat); //there it is
  }

I'd like to chain the methods but it is not working at all. This is what I came up with:

let gastronomies = await knex
  .from('user')
  .select('*', {key: 'user.id'})
  .innerJoin('profile', 'user.id', 'profile.user_id')
  .where('user.status', 1);

if(args.lat)
    gastronomies.where('lat', 'like', args.lat);

But it says that gastronomies does not have a method called "where". Any suggestions?

widdy
  • 426
  • 5
  • 21

2 Answers2

1

Check out the docs - you can pass in multiple where clauses using an object:

.where({ first_name: 'Test', last_name: 'User' })

http://knexjs.org/#Builder-where

Aaria Carter-Weir
  • 1,639
  • 12
  • 17
1

If you want to chain it you should wait with async/await, cause it will trigger call to database. I'd do it like that:

const gastronomies = knex // no await here
  .from('user')
  .select('*', {key: 'user.id'})
  .innerJoin('profile', 'user.id', 'profile.user_id')
  .where('user.status', 1);

if(args.lat)
    gastronomies.where('lat', 'like', args.lat);

const response = await gastronomies;

You can also check answer to your question with promises here: Can I conditionally add a where() clause to my knex query?

sdooo
  • 1,851
  • 13
  • 20
  • 1
    Your answer works, thank you! I build my query without "await", chain it with with my conditions and after that i just do "return await gastronomies" and it works fine! – widdy May 02 '18 at 07:03