Add queryBuilder as first parameter to queryBuilder.modify

This commit is contained in:
Jani Evakallio 2015-07-16 15:49:30 +01:00
parent 299bbfa60b
commit cb89930155
4 changed files with 13 additions and 8 deletions

View File

@ -1376,12 +1376,12 @@ knex('accounts').truncate()
<b class="header">modify</b><code>.modify(fn, *arguments)</code>
<br />
Allows encapsulating and re-using query snippets and common behaviors as functions.
The first parameter is a callback whose this context is bound to the current query chain.
Rest of the (optional) parameters are passed to the callback.
The callback function should receive the query builder as its first argument, followed by
the rest of the (optional) parameters passed to modify.
<pre>
<code class="js">var withUserName = function(foreignKey) {
this
<code class="js">var withUserName = function(queryBuilder, foreignKey) {
queryBuilder
.leftJoin('users', foreignKey, 'users.id')
.select('users.user_name');
};

View File

@ -694,7 +694,7 @@ assign(Builder.prototype, {
// Passes query to provided callback function, useful for e.g. composing
// domain-specific helpers
modify: function modify(callback) {
callback.apply(this, _.rest(arguments));
callback.apply(this, [this].concat(_.rest(arguments)));
return this;
},

View File

@ -692,7 +692,7 @@ assign(Builder.prototype, {
// Passes query to provided callback function, useful for e.g. composing
// domain-specific helpers
modify: function(callback) {
callback.apply(this, _.rest(arguments));
callback.apply(this, [this].concat(_.rest(arguments)));
return this;
},

View File

@ -2346,8 +2346,13 @@ describe("QueryBuilder", function() {
})
it('has a modify method which accepts a function that can modify the query', function() {
// arbitrary number of arguments can be passed to `.modify`, builder is bound to `this`
var withBars = function(table, fk) {
// arbitrary number of arguments can be passed to `.modify(queryBuilder, ...)`,
// builder is bound to `this`
var withBars = function(queryBuilder, table, fk) {
if(!this || this !== queryBuilder) {
throw 'Expected query builder passed as first argument and bound as `this` context';
}
this
.leftJoin('bars', table + '.' + fk, 'bars.id')
.select('bars.*')