Prevent multiple (identical) joins of the same table
See original GitHub issueI noticed that a new object contains an array for joins, and I was wondering if there was some way to keep track that there would be no duplicate joins. I’m currently building a complicated query builder / api where it’s possible I might join the same table the same way multiple times (which results in a SQL error).
Here’s the situation:
var db = Knex.initialize({ ..connection stuff ...});
var person = db('persons');
var query = req.query;
if(typeof query.shoe !== 'undefined') {
person.join('clothes', 'person.clothes_id', '=', 'clothes.id');
person.join('shoes', 'clothes.shoe_id', '=', 'shoes.id');
}
if(typeof query.shirt !== 'undefined') {
person.join('clothes', 'person.clothes_id', '=', 'clothes.id');
person.join('shirts', 'clothes.shirt_id', '=', 'shirts.id');
}
This would result in an error since we’re joining “clothes” twice. So, I originally tried to create an internal “joined table” collection + a wrapper for the join:
var person = db('persons');
person.joinTables = [];
person.preJoin = function(table, col1, operator, col2){
if(_.contains(this.joinTables, table)) {
//make chainable;
return this;
}
else {
this.joinTables.push(table);
return this.join(table, col1, operator, col2);
}
}
However, I found that while I can easily access the “joinTables” array, the function itself is not accessible. I’m guessing due to the response handler or the way Knex is built with its grammar.js or whatever else.
Any ideas on how I could either implement this function and make it work or have a safety on Knex to allow multiple identical joins? perhaps a check against the joins array to see if an identical entry has been made?
Issue Analytics
- State:
- Created 10 years ago
- Comments:5
Top GitHub Comments
My current workaround is
which is quite verbose…
You may want to utilize and abstract around the
builder.queryContext()
function found here