Search…
When / Conditionals
If you store the builder object in a variable, you can use if and else statements like you would expect.
QueryBuilder
1
var q = query.from( "posts" );
2
if ( someFlag ) {
3
q.orderBy( "published_date", "desc" );
4
}
Copied!
This works, but breaks chainability. To keep chainability you can use the when helper method.

when

Name
Type
Required
Default
Description
condition
boolean
true
The condition to switch on.
onTrue
Function
true
The callback to execute if the condition is true. It is passed the builder object as the only parameter.
onFalse
Function
false
function( q ) { return q; }
The callback to execute if the conditions is false. It is passed the builder object as the only parameter.
withoutScoping
boolean
false
false
Flag to turn off the automatic scoping of where clauses during the callback.
The when helper is used to allow conditional statements when defining queries without using if statements and having to store temporary variables.
QueryBuilder
1
query.from( "posts" )
2
.when( someFlag, function( q ) {
3
q.orderBy( "published_date", "desc" );
4
} )
5
.get();
Copied!
You can pass a third argument to be called in the else case.
QueryBuilder
1
query.from( "posts" )
2
.when(
3
someFlag,
4
function( q ) {
5
q.orderBy( "published_date", "desc" );
6
},
7
function( q ) {
8
q.orderBy( "modified_date", "desc" );
9
}
10
);
Copied!
when callbacks are automatically scoped and grouped. That means that if a where clause is added inside the callback with an OR combinator the clauses will automatically be grouped (have parenthesis put around them.) You can disable this feature by passing withoutScoping = true to the when callback.
1
qb.from( "users" )
2
.where( "active", 1 )
3
.when( len( url.q ), function( q ) {
4
q.where( "username", "LIKE", q & "%" )
5
.orWhere( "email", "LIKE", q & "%" );
6
} );
Copied!
1
SELECT *
2
FROM "users"
3
WHERE "active" = ?
4
AND (
5
"username" = ?
6
OR "email" = ?
7
)
Copied!
Last modified 1yr ago
Copy link
Contents
when