Knex: is it possible to build nested Join query?

Created on 21 Apr 2016  ·  3Comments  ·  Source: knex/knex

Hi, Great work by Knexjs team. I am trying out knexjs over ORM with one small example having many to many relationship. The Example is of Authors and Books where auhtors table and book table have many to many relationship through author_books table. I want to get particular book with all the authors. Below is raw query which gives the expected result. But I am not getting how to build this query using Knexjs? Any help would be appreciated.

Note: I am using Knexjs with javascript ES6.

Query:-

SELECT  `book`.`id` ,  `book`.`title` ,  `authors`.`id` AS  `authors.id` ,  `authors`.`name`
AS  `authors.authorname` ,  `authors.author_books`.`book_id` 
AS  `authors.author_books.bookId` , `authors.author_books`.`author_id` 
AS  `authors.author_books.author_id` 
FROM  `books` AS  `book` 
LEFT OUTER JOIN (
 `author_books` AS  `authors.author_books` 
INNER JOIN  `authors` AS  `authors` ON  `authors`.`id` =  `authors.author_books`.`author_id`
) ON  `book`.`id` =  `authors.author_books`.`book_id` 
WHERE  `book`.`id` =1

this is the query I am trying to build using Knexjs.

this.Knex('books as book')
.leftOuterJoin('author_books as authors.author_books', function(){
  // How could I nest INNER JOIN in LEFT OUTER JOIN

  this.on('book.id', 'authors.author_books.book_id')
}).select('book.id', 'book.title', 'authors.id as authors.id'
  , 'authors.name as authors.name', 'authors.author_books.book_id as authors.author_books.book_id'
  , 'authors.author_books.author_id as authors.auhtor_books.author_id')
.where('book.id', id)

Please let me know if I am Wrong somewhere?

question

Most helpful comment

The question is how to nest join queries using knexjs? Inner Join nested with Left or Right JOIN using knex, so that knex can build SQL query as shown above in Query: section?

All 3 comments

The question is how to nest join queries using knexjs? Inner Join nested with Left or Right JOIN using knex, so that knex can build SQL query as shown above in Query: section?

@saurabhghewari did you ever find a solution for this question? I'm trying to do something similar.

I have to say I'm not sure if knex supports nested joins at all... I didn't see any tests or documentation for that case, so I'm pretty sure they are not supported. Please add feature request for this.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

tjwebb picture tjwebb  ·  3Comments

mattgrande picture mattgrande  ·  3Comments

PaulOlteanu picture PaulOlteanu  ·  3Comments

arconus picture arconus  ·  3Comments

nklhrstv picture nklhrstv  ·  3Comments