Saajidh Borham
Saajidh Borham

Reputation: 59

How to do a nested query get the expected result using knex?

There are 3 tables called warehouses, agents_Warehouses, and agents. agents_warehouses table is connected with warehouses table and agents table.

agents_warehouses table

So I need to get warehouses that NOT IN agents_warehouses table.

This is the sql query I need to do from knex.js;

SELECT id, name FROM `warehouses` 
WHERE id not in 
(SELECT warehouse_id as id from agents_warehouses WHERE agent_id=2)

How do I get my expected result using knex.js?

Upvotes: 1

Views: 453

Answers (1)

felixmosh
felixmosh

Reputation: 35603

You can build the required query with something like this:

knex('warehouses')
  .columns(['id', 'name'])
  .whereNotIn('id', knex('agents_warehouses').column('warehouse_id').where('agent_id', 2));

Upvotes: 3

Related Questions