Query Builder

Create custom queries in an object oriented way, closely following SQL syntax.

The QueryBuilder class provides a way to build custom queries in a very similar way to SQL, but using class and property names rather than table and column names (thus decoupling your code from the database, making it easier to make changes to either of them). You can use it to create select, insert, update, or delete queries.

In the basic usage examples, the criteria to use when loading records is specified using an associative array, where the key is the property name, and the value can be either a single scalar value (in which case it is assumed that the operator is '='), or an array describing the operator and value(s) to use. Where more than one element is defined, the elements are joined together with 'AND'.

The query builder allows much more flexibility, allowing you to create select, insert, update, and delete queries, including nested OR and AND criteria, custom joins on multiple conditions, partial object hydration, and the ability to use SQL functions and expressions.

Creating a Query Builder

The QueryBuilder class is its own static factory (although technically, this breaks the single responsibility principle, it leads to cleaner userland code), so you can create a query builder just by calling the static method: QueryBuilder::create(). If you want to keep your code even more concise, you can use the alias QB instead of QueryBuilder.

Most of the methods on the query builder return the instance itself ($this), so you can use method chaining to create natural looking queries.

$query = QueryBuilder::create()
    ->select('id', 'name', 'email')
    ->from(User::class)
    ->where('dateOfBirth', '>', '2000-01-01')
    ->orderBy(['name' => 'DESC'])
    ->buildSelectQuery();

You do not have to call all of those methods. If you just want to populate all properties of whichever class is set on the repository, ordered by primary key, you can just call the where method (you could even omit that too, but it would then be the same as just calling the findAll method on the repository, so there is no point):

$query = QueryBuilder::create()
    ->where('dateOfBirth', '>', '2000-01-01')
    ->buildSelectQuery();

More information about the different types of query you can build, with examples, are shown in the pages that follow.

Last updated