Running a Query
How to execute a custom query you created with the query builder.
Executing queries
Any query can be executed by calling the executeQuery method on a repository. The return value will depend on the type of query - a select query will return one or more entities, but insert, update, and delete queries will return the number of database records that were affected by the query.
$query = QueryBuilder::create()
->select('firstName', 'lastName')
->from(Contact::class)
->where('lastName', '=', 'Skywalker')
->buildSelectQuery();
$contacts = $repository->executeQuery($query);
// $contacts now contains a list of partially
// hydrated Contact objects for each matching
// contact.$query = QueryBuilder::create()
->delete(Contact::class)
->where('isPermanent', '=', false)
->buildDeleteQuery();
$affectedCount = $repository->executeQuery($query);
// $affectedCount now contains the count of how
// many records were deleted.Queries with find methods
In addition to executeQuery, you can pass a select query to any of the find methods on a repository (instead of an array of criteria). This allows you to do things like call findValuesBy and get an indexed array back instead of entities.
$query = QueryBuilder::create()
->select('firstName')
->from(Contact::class)
->where('lastName', '=', 'Skywalker')
->buildSelectQuery();
$contacts = $repository->findValuesBy($query);
// $contacts now contains:
// ['Luke', 'Anakin']Or get an associative array:
$repository->setConfigOption(ConfigOptions::BIND_TO_ENTITIES, false);
$query = QueryBuilder::create()
->select('firstName', 'lastName')
->from(Contact::class)
->where('lastName', '=', 'Skywalker')
->buildSelectQuery();
$contacts = $repository->findBy($query);
// $contacts now contains:
// [
// ['firstName' => 'Luke', 'lastName' => 'Skywalker'],
// ['firstName' => 'Anakin', 'lastName' => 'Skywalker']
// ]Last updated
Was this helpful?