Conditionals

Basic if and else

If you store the builder object in a variable, you can use if and else statements like you would expect.

var builder = builder.from( "posts" );
if ( rc.recent ) {
    builder.orderBy( "published_date", "desc" );
}
var results = builder.get();

This works, but breaks chainability. A better way is to use the when helper method.

when

We can rewrite the above query like so:

var results = builder.from( "posts" )
    .when( rc.recent, function( q ) {
        q.orderBy( "published_date", "desc" );
    } )
    .get();

Nice. We keep chainability this way and reduce the number of temporary variables we need.

Last updated