Skip to content
Laran Evans edited this page Mar 27, 2016 · 1 revision

GQL doesn't explicitly add joins to your query builder. However, during gql.parse() it extracts the names of the tables that were referenced in the GQL string. These table names are available via .relations()

For example:

var _ = require('lodash');
var knex = require('knex');

// Our query
var query = 'posts.title:\'The Best Post Ever\'+comments.created_at:>=\'2016-01-01\'';

var parsedQuery = gql.parse(_gql);

// At this point parsedQuery.relations() will return ['posts', 'comments']

// ---
// We can now do something like this to programmatically join the tables relevant to the query.
// ---

// A referential model for our tables. Could store for many different relations in the same object.
var metadata = {posts: {comments: ['posts.id', 'comments.post_id']}};

// The table/collection we're selecting from.
var table = 'posts';

var relations = parsedQuery.relations(); // the tables referenced in our GQL query
var structure = metadata[table];         // the metadata we need to join the referenced tables
var queryBuilder = knex(table);          // a knex object referencing our base table

// Apply the relevant joins
for(var i = 0; i < relations.length; i += 1) {
  var joinArgs = _.concat([relations[i]], structure[relations[i]]); // => ['comments', 'posts.id', 'comments.post_id']
  
  // Any type of join would be allowed. I just happen to use innerJoin here.
  knex.innerJoin.apply(queryBuilder, joinArgs);
}

// .applyTo() could be called before or after applying the joins. Doesn't matter.
var resultsPromise = parsedQuery.applyTo(queryBuilder).select('*');

Clone this wiki locally