widdy
widdy

Reputation: 446

javascript method chaining - knex.js

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?

Upvotes: 0

Views: 645

Answers (2)

sdooo
sdooo

Reputation: 1881

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?

Upvotes: 1

Aaria Carter-Weir
Aaria Carter-Weir

Reputation: 1679

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

Upvotes: 1

Related Questions