Documentation

QueryBuilder
in package

This class is responsible for building DQL query strings via an object oriented PHP interface.

Table of Contents

Constants

DELETE  = 1
SELECT  = 0
STATE_CLEAN  = 1
STATE_DIRTY  = 0
UPDATE  = 2

Properties

$cacheable  : bool
Whether to use second level cache, if available.
$cacheMode  : int|null
Second level query cache mode.
$cacheRegion  : string|null
Second level cache region name.
$lifetime  : int
$dql  : string|null
The complete DQL string for this query.
$dqlParts  : mixed
The array of DQL parts collected.
$em  : EntityManagerInterface
The EntityManager used by this QueryBuilder.
$firstResult  : int
The index of the first result to retrieve.
$joinRootAliases  : mixed
Keeps root entity alias names for join entities.
$maxResults  : int|null
The maximum number of results to retrieve.
$parameters  : ArrayCollection
The query parameters.
$state  : int
The state of the query object. Can be dirty or clean.
$type  : int
The type of query this is. Can be select, update or delete.

Methods

__clone()  : void
Deep clones all expression objects in the DQL parts.
__construct()  : mixed
Initializes a new <tt>QueryBuilder</tt> that uses the given <tt>EntityManager</tt>.
__toString()  : string
Gets a string representation of this QueryBuilder which corresponds to the final DQL query being constructed.
add()  : $this
Either appends to or replaces a single, generic query part.
addCriteria()  : $this
Adds criteria to the query.
addGroupBy()  : $this
Adds a grouping expression to the query.
addOrderBy()  : $this
Adds an ordering to the query results.
addSelect()  : $this
Adds an item that is to be returned in the query result.
andHaving()  : $this
Adds a restriction over the groups of the query, forming a logical conjunction with any existing having restrictions.
andWhere()  : $this
Adds one or more restrictions to the query results, forming a logical conjunction with any previously specified restrictions.
delete()  : $this
Turns the query being built into a bulk delete query that ranges over a certain entity type.
distinct()  : $this
Adds a DISTINCT flag to this query.
expr()  : Expr
Gets an ExpressionBuilder used for object-oriented construction of query expressions.
from()  : $this
Creates and adds a query root corresponding to the entity identified by the given alias, forming a cartesian product with any existing query roots.
getAllAliases()  : array<string|int, string>
Gets all the aliases that have been used in the query.
getCacheMode()  : int|null
getCacheRegion()  : string|null
Obtain the name of the second level query cache region in which query results will be stored
getDQL()  : string
Gets the complete DQL string formed by the current specifications of this QueryBuilder.
getDQLPart()  : mixed
Gets a query part by its name.
getDQLParts()  : mixed
Gets all query parts.
getEntityManager()  : EntityManagerInterface
Gets the associated EntityManager for this query builder.
getFirstResult()  : int|null
Gets the position of the first result the query object was set to retrieve (the "offset").
getLifetime()  : int
getMaxResults()  : int|null
Gets the maximum number of results the query object was set to retrieve (the "limit").
getParameter()  : Parameter|null
Gets a (previously set) query parameter of the query being constructed.
getParameters()  : ArrayCollection
Gets all defined query parameters for the query being constructed.
getQuery()  : Query
Constructs a Query instance from the current specifications of the builder.
getRootAlias()  : string
Gets the FIRST root alias of the query. This is the first entity alias involved in the construction of the query.
getRootAliases()  : array<string|int, string>
Gets the root aliases of the query. This is the entity aliases involved in the construction of the query.
getRootEntities()  : array<string|int, string>
Gets the root entities of the query. This is the entity aliases involved in the construction of the query.
getState()  : int
Gets the state of this query builder instance.
getType()  : int
Gets the type of the currently built query.
groupBy()  : $this
Specifies a grouping over the results of the query.
having()  : $this
Specifies a restriction over the groups of the query.
indexBy()  : $this
Updates a query root corresponding to an entity setting its index by. This method is intended to be used with EntityRepository->createQueryBuilder(), which creates the initial FROM clause and do not allow you to update it setting an index by.
innerJoin()  : $this
Creates and adds a join over an entity association to the query.
isCacheable()  : bool
Are the query results enabled for second level cache?
join()  : $this
Creates and adds a join over an entity association to the query.
leftJoin()  : $this
Creates and adds a left join over an entity association to the query.
orderBy()  : $this
Specifies an ordering for the query results.
orHaving()  : $this
Adds a restriction over the groups of the query, forming a logical disjunction with any existing having restrictions.
orWhere()  : $this
Adds one or more restrictions to the query results, forming a logical disjunction with any previously specified restrictions.
resetDQLPart()  : $this
Resets single DQL part.
resetDQLParts()  : $this
Resets DQL parts.
select()  : $this
Specifies an item that is to be returned in the query result.
set()  : $this
Sets a new value for a field in a bulk update query.
setCacheable()  : $this
Enable/disable second level query (result) caching for this query.
setCacheMode()  : $this
setCacheRegion()  : $this
setFirstResult()  : $this
Sets the position of the first result to retrieve (the "offset").
setLifetime()  : $this
Sets the life-time for this query into second level cache.
setMaxResults()  : $this
Sets the maximum number of results to retrieve (the "limit").
setParameter()  : $this
Sets a query parameter for the query being constructed.
setParameters()  : $this
Sets a collection of query parameters for the query being constructed.
update()  : $this
Turns the query being built into a bulk update query that ranges over a certain entity type.
where()  : $this
Specifies one or more restrictions to the query result.
findRootAlias()  : string
Finds the root entity alias of the joined entity.
getDQLForDelete()  : string
getDQLForSelect()  : string
getDQLForUpdate()  : string
getReducedDQLQueryPart()  : string

Constants

STATE_CLEAN

public mixed STATE_CLEAN = 1
Tags
deprecated

STATE_DIRTY

public mixed STATE_DIRTY = 0
Tags
deprecated

Properties

$cacheable

Whether to use second level cache, if available.

protected bool $cacheable = false

$cacheMode

Second level query cache mode.

protected int|null $cacheMode
Tags
psalm-var

Cache::MODE_*|null

$cacheRegion

Second level cache region name.

protected string|null $cacheRegion

$dql

The complete DQL string for this query.

private string|null $dql

$dqlParts

The array of DQL parts collected.

private mixed $dqlParts = ['distinct' => false, 'select' => [], 'from' => [], 'join' => [], 'set' => [], 'where' => null, 'groupBy' => [], 'having' => null, 'orderBy' => []]
Tags
psalm-var

array<string, mixed>

$firstResult

The index of the first result to retrieve.

private int $firstResult = 0

$joinRootAliases

Keeps root entity alias names for join entities.

private mixed $joinRootAliases = []
Tags
psalm-var

array<string, string>

$maxResults

The maximum number of results to retrieve.

private int|null $maxResults = null

$state

The state of the query object. Can be dirty or clean.

private int $state = self::STATE_CLEAN
Tags
psalm-var

self::STATE_*

$type

The type of query this is. Can be select, update or delete.

private int $type = self::SELECT
Tags
psalm-var

self::SELECT|self::DELETE|self::UPDATE

Methods

__clone()

Deep clones all expression objects in the DQL parts.

public __clone() : void

__toString()

Gets a string representation of this QueryBuilder which corresponds to the final DQL query being constructed.

public __toString() : string
Return values
string

The string representation of this QueryBuilder.

add()

Either appends to or replaces a single, generic query part.

public add(string $dqlPartName, string|object|array<string|int, mixed> $dqlPart[, bool $append = false ]) : $this

The available parts are: 'select', 'from', 'join', 'set', 'where', 'groupBy', 'having' and 'orderBy'.

Parameters
$dqlPartName : string

The DQL part name.

$dqlPart : string|object|array<string|int, mixed>

An Expr object.

$append : bool = false

Whether to append (true) or replace (false).

Tags
psalm-param

string|object|list|array{join: array<int|string, object>} $dqlPart

Return values
$this

addCriteria()

Adds criteria to the query.

public addCriteria(Criteria $criteria) : $this

Adds where expressions with AND operator. Adds orderings. Overrides firstResult and maxResults if they're set.

Parameters
$criteria : Criteria
Tags
throws
QueryException
Return values
$this

addGroupBy()

Adds a grouping expression to the query.

public addGroupBy(string $groupBy) : $this
$qb = $em->createQueryBuilder() ->select('u') ->from('User', 'u') ->groupBy('u.lastLogin') ->addGroupBy('u.createdAt');
Parameters
$groupBy : string

The grouping expression.

Return values
$this

addOrderBy()

Adds an ordering to the query results.

public addOrderBy(string|OrderBy $sort[, string|null $order = null ]) : $this
Parameters
$sort : string|OrderBy

The ordering expression.

$order : string|null = null

The ordering direction.

Return values
$this

addSelect()

Adds an item that is to be returned in the query result.

public addSelect([mixed $select = null ]) : $this
$qb = $em->createQueryBuilder() ->select('u') ->addSelect('p') ->from('User', 'u') ->leftJoin('u.Phonenumbers', 'p');
Parameters
$select : mixed = null

The selection expression.

Return values
$this

andHaving()

Adds a restriction over the groups of the query, forming a logical conjunction with any existing having restrictions.

public andHaving(mixed $having) : $this
Parameters
$having : mixed

The restriction to append.

Return values
$this

andWhere()

Adds one or more restrictions to the query results, forming a logical conjunction with any previously specified restrictions.

public andWhere() : $this
$qb = $em->createQueryBuilder() ->select('u') ->from('User', 'u') ->where('u.username LIKE ?') ->andWhere('u.is_active = 1');
Tags
see
where()
Return values
$this

delete()

Turns the query being built into a bulk delete query that ranges over a certain entity type.

public delete([string|null $delete = null ][, string|null $alias = null ]) : $this
$qb = $em->createQueryBuilder() ->delete('User', 'u') ->where('u.id = :user_id') ->setParameter('user_id', 1);
Parameters
$delete : string|null = null

The class/type whose instances are subject to the deletion.

$alias : string|null = null

The class/type alias used in the constructed query.

Return values
$this

distinct()

Adds a DISTINCT flag to this query.

public distinct([bool $flag = true ]) : $this
$qb = $em->createQueryBuilder() ->select('u') ->distinct() ->from('User', 'u');
Parameters
$flag : bool = true
Return values
$this

expr()

Gets an ExpressionBuilder used for object-oriented construction of query expressions.

public expr() : Expr

This producer method is intended for convenient inline usage. Example:

$qb = $em->createQueryBuilder(); $qb ->select('u') ->from('User', 'u') ->where($qb->expr()->eq('u.id', 1));

For more complex expression construction, consider storing the expression builder object in a local variable.

Return values
Expr

from()

Creates and adds a query root corresponding to the entity identified by the given alias, forming a cartesian product with any existing query roots.

public from(string $from, string $alias[, string|null $indexBy = null ]) : $this
$qb = $em->createQueryBuilder() ->select('u') ->from('User', 'u');
Parameters
$from : string

The class name.

$alias : string

The alias of the class.

$indexBy : string|null = null

The index for the from.

Return values
$this

getAllAliases()

Gets all the aliases that have been used in the query.

public getAllAliases() : array<string|int, string>

Including all select root aliases and join aliases

$qb = $em->createQueryBuilder() ->select('u') ->from('User', 'u') ->join('u.articles','a');
$qb->getAllAliases(); // array('u','a')
Tags
psalm-return

list

Return values
array<string|int, string>

getCacheMode()

public getCacheMode() : int|null
Tags
psalm-return

Cache::MODE_*|null

Return values
int|null

getCacheRegion()

Obtain the name of the second level query cache region in which query results will be stored

public getCacheRegion() : string|null
Return values
string|null

The cache region name; NULL indicates the default region.

getDQL()

Gets the complete DQL string formed by the current specifications of this QueryBuilder.

public getDQL() : string
$qb = $em->createQueryBuilder() ->select('u') ->from('User', 'u'); echo $qb->getDql(); // SELECT u FROM User u
Return values
string

The DQL query string.

getDQLPart()

Gets a query part by its name.

public getDQLPart(string $queryPartName) : mixed
Parameters
$queryPartName : string
Return values
mixed

$queryPart

getDQLParts()

Gets all query parts.

public getDQLParts() : mixed
Tags
psalm-return

array<string, mixed> $dqlParts

getFirstResult()

Gets the position of the first result the query object was set to retrieve (the "offset").

public getFirstResult() : int|null

Returns NULL if was not applied to this QueryBuilder.

Return values
int|null

The position of the first result.

getLifetime()

public getLifetime() : int
Return values
int

getMaxResults()

Gets the maximum number of results the query object was set to retrieve (the "limit").

public getMaxResults() : int|null

Returns NULL if was not applied to this query builder.

Return values
int|null

Maximum number of results.

getParameter()

Gets a (previously set) query parameter of the query being constructed.

public getParameter(string|int $key) : Parameter|null
Parameters
$key : string|int

The key (index or name) of the bound parameter.

Return values
Parameter|null

The value of the bound parameter.

getParameters()

Gets all defined query parameters for the query being constructed.

public getParameters() : ArrayCollection
Tags
psalm-return

ArrayCollection<int, Parameter>

Return values
ArrayCollection

The currently defined query parameters.

getQuery()

Constructs a Query instance from the current specifications of the builder.

public getQuery() : Query
$qb = $em->createQueryBuilder() ->select('u') ->from('User', 'u'); $q = $qb->getQuery(); $results = $q->execute();
Return values
Query

getRootAlias()

Gets the FIRST root alias of the query. This is the first entity alias involved in the construction of the query.

public getRootAlias() : string
$qb = $em->createQueryBuilder() ->select('u') ->from('User', 'u');

echo $qb->getRootAlias(); // u

Tags
deprecated

Please use $qb->getRootAliases() instead.

throws
RuntimeException
Return values
string

getRootAliases()

Gets the root aliases of the query. This is the entity aliases involved in the construction of the query.

public getRootAliases() : array<string|int, string>
$qb = $em->createQueryBuilder() ->select('u') ->from('User', 'u');
$qb->getRootAliases(); // array('u')
Tags
psalm-return

list

Return values
array<string|int, string>

getRootEntities()

Gets the root entities of the query. This is the entity aliases involved in the construction of the query.

public getRootEntities() : array<string|int, string>
$qb = $em->createQueryBuilder() ->select('u') ->from('User', 'u');
$qb->getRootEntities(); // array('User')
Tags
psalm-return

list

Return values
array<string|int, string>

getState()

Gets the state of this query builder instance.

public getState() : int
Tags
deprecated

The builder state is an internal concern.

psalm-return

self::STATE_*

Return values
int

Either QueryBuilder::STATE_DIRTY or QueryBuilder::STATE_CLEAN.

getType()

Gets the type of the currently built query.

public getType() : int
Tags
deprecated

If necessary, track the type of the query being built outside of the builder.

psalm-return

self::SELECT|self::DELETE|self::UPDATE

Return values
int

groupBy()

Specifies a grouping over the results of the query.

public groupBy(string $groupBy) : $this

Replaces any previously specified groupings, if any.

$qb = $em->createQueryBuilder() ->select('u') ->from('User', 'u') ->groupBy('u.id');
Parameters
$groupBy : string

The grouping expression.

Return values
$this

having()

Specifies a restriction over the groups of the query.

public having(mixed $having) : $this

Replaces any previous having restrictions, if any.

Parameters
$having : mixed

The restriction over the groups.

Return values
$this

indexBy()

Updates a query root corresponding to an entity setting its index by. This method is intended to be used with EntityRepository->createQueryBuilder(), which creates the initial FROM clause and do not allow you to update it setting an index by.

public indexBy(string $alias, string $indexBy) : $this
$qb = $userRepository->createQueryBuilder('u') ->indexBy('u', 'u.id');
// Is equivalent to...

$qb = $em->createQueryBuilder()
    ->select('u')
    ->from('User', 'u', 'u.id');
Parameters
$alias : string

The root alias of the class.

$indexBy : string

The index for the from.

Tags
throws
QueryException
Return values
$this

innerJoin()

Creates and adds a join over an entity association to the query.

public innerJoin(string $join, string $alias[, string|null $conditionType = null ][, string|Comparison|Composite|Func|null $condition = null ][, string|null $indexBy = null ]) : $this

The entities in the joined association will be fetched as part of the query result if the alias used for the joined association is placed in the select expressions.

[php]
$qb = $em->createQueryBuilder()
    ->select('u')
    ->from('User', 'u')
    ->innerJoin('u.Phonenumbers', 'p', Expr\Join::WITH, 'p.is_primary = 1');
Parameters
$join : string

The relationship to join.

$alias : string

The alias of the join.

$conditionType : string|null = null

The condition type constant. Either ON or WITH.

$condition : string|Comparison|Composite|Func|null = null

The condition for the join.

$indexBy : string|null = null

The index for the join.

Tags
psalm-param

Expr\Join::ON|Expr\Join::WITH|null $conditionType

Return values
$this

isCacheable()

Are the query results enabled for second level cache?

public isCacheable() : bool
Return values
bool

join()

Creates and adds a join over an entity association to the query.

public join(string $join, string $alias[, string|null $conditionType = null ][, string|Comparison|Composite|Func|null $condition = null ][, string|null $indexBy = null ]) : $this

The entities in the joined association will be fetched as part of the query result if the alias used for the joined association is placed in the select expressions.

$qb = $em->createQueryBuilder() ->select('u') ->from('User', 'u') ->join('u.Phonenumbers', 'p', Expr\Join::WITH, 'p.is_primary = 1');
Parameters
$join : string

The relationship to join.

$alias : string

The alias of the join.

$conditionType : string|null = null

The condition type constant. Either ON or WITH.

$condition : string|Comparison|Composite|Func|null = null

The condition for the join.

$indexBy : string|null = null

The index for the join.

Tags
psalm-param

Expr\Join::ON|Expr\Join::WITH|null $conditionType

Return values
$this

leftJoin()

Creates and adds a left join over an entity association to the query.

public leftJoin(string $join, string $alias[, string|null $conditionType = null ][, string|Comparison|Composite|Func|null $condition = null ][, string|null $indexBy = null ]) : $this

The entities in the joined association will be fetched as part of the query result if the alias used for the joined association is placed in the select expressions.

$qb = $em->createQueryBuilder() ->select('u') ->from('User', 'u') ->leftJoin('u.Phonenumbers', 'p', Expr\Join::WITH, 'p.is_primary = 1');
Parameters
$join : string

The relationship to join.

$alias : string

The alias of the join.

$conditionType : string|null = null

The condition type constant. Either ON or WITH.

$condition : string|Comparison|Composite|Func|null = null

The condition for the join.

$indexBy : string|null = null

The index for the join.

Tags
psalm-param

Expr\Join::ON|Expr\Join::WITH|null $conditionType

Return values
$this

orderBy()

Specifies an ordering for the query results.

public orderBy(string|OrderBy $sort[, string|null $order = null ]) : $this

Replaces any previously specified orderings, if any.

Parameters
$sort : string|OrderBy

The ordering expression.

$order : string|null = null

The ordering direction.

Return values
$this

orHaving()

Adds a restriction over the groups of the query, forming a logical disjunction with any existing having restrictions.

public orHaving(mixed $having) : $this
Parameters
$having : mixed

The restriction to add.

Return values
$this

orWhere()

Adds one or more restrictions to the query results, forming a logical disjunction with any previously specified restrictions.

public orWhere() : $this
$qb = $em->createQueryBuilder() ->select('u') ->from('User', 'u') ->where('u.id = 1') ->orWhere('u.id = 2');
Tags
see
where()
Return values
$this

resetDQLPart()

Resets single DQL part.

public resetDQLPart(string $part) : $this
Parameters
$part : string
Return values
$this

resetDQLParts()

Resets DQL parts.

public resetDQLParts([array<string|int, string>|null $parts = null ]) : $this
Parameters
$parts : array<string|int, string>|null = null
Tags
psalm-param

list|null $parts

Return values
$this

select()

Specifies an item that is to be returned in the query result.

public select([mixed $select = null ]) : $this

Replaces any previously specified selections, if any.

$qb = $em->createQueryBuilder() ->select('u', 'p') ->from('User', 'u') ->leftJoin('u.Phonenumbers', 'p');
Parameters
$select : mixed = null

The selection expressions.

Return values
$this

set()

Sets a new value for a field in a bulk update query.

public set(string $key, mixed $value) : $this
$qb = $em->createQueryBuilder() ->update('User', 'u') ->set('u.password', '?1') ->where('u.id = ?2');
Parameters
$key : string

The key/field to set.

$value : mixed

The value, expression, placeholder, etc.

Return values
$this

setCacheable()

Enable/disable second level query (result) caching for this query.

public setCacheable(bool $cacheable) : $this
Parameters
$cacheable : bool
Return values
$this

setCacheMode()

public setCacheMode(int $cacheMode) : $this
Parameters
$cacheMode : int
Tags
psalm-param

Cache::MODE_* $cacheMode

Return values
$this

setCacheRegion()

public setCacheRegion(string $cacheRegion) : $this
Parameters
$cacheRegion : string
Return values
$this

setFirstResult()

Sets the position of the first result to retrieve (the "offset").

public setFirstResult(int|null $firstResult) : $this
Parameters
$firstResult : int|null

The first result to return.

Return values
$this

setLifetime()

Sets the life-time for this query into second level cache.

public setLifetime(int $lifetime) : $this
Parameters
$lifetime : int
Return values
$this

setMaxResults()

Sets the maximum number of results to retrieve (the "limit").

public setMaxResults(int|null $maxResults) : $this
Parameters
$maxResults : int|null

The maximum number of results to retrieve.

Return values
$this

setParameter()

Sets a query parameter for the query being constructed.

public setParameter(string|int $key, mixed $value[, string|int|null $type = null ]) : $this
$qb = $em->createQueryBuilder() ->select('u') ->from('User', 'u') ->where('u.id = :user_id') ->setParameter('user_id', 1);
Parameters
$key : string|int

The parameter position or name.

$value : mixed

The parameter value.

$type : string|int|null = null

ParameterType::* or \Doctrine\DBAL\Types\Type::* constant

Return values
$this

setParameters()

Sets a collection of query parameters for the query being constructed.

public setParameters(ArrayCollection|array<string|int, mixed> $parameters) : $this
$qb = $em->createQueryBuilder() ->select('u') ->from('User', 'u') ->where('u.id = :user_id1 OR u.id = :user_id2') ->setParameters(new ArrayCollection(array( new Parameter('user_id1', 1), new Parameter('user_id2', 2) )));
Parameters
$parameters : ArrayCollection|array<string|int, mixed>

The query parameters to set.

Tags
psalm-param

ArrayCollection<int, Parameter>|mixed[] $parameters

Return values
$this

update()

Turns the query being built into a bulk update query that ranges over a certain entity type.

public update([string|null $update = null ][, string|null $alias = null ]) : $this
$qb = $em->createQueryBuilder() ->update('User', 'u') ->set('u.password', '?1') ->where('u.id = ?2');
Parameters
$update : string|null = null

The class/type whose instances are subject to the update.

$alias : string|null = null

The class/type alias used in the constructed query.

Return values
$this

where()

Specifies one or more restrictions to the query result.

public where(mixed $predicates) : $this

Replaces any previously specified restrictions, if any.

$qb = $em->createQueryBuilder() ->select('u') ->from('User', 'u') ->where('u.id = ?');
// You can optionally programmatically build and/or expressions
$qb = $em->createQueryBuilder();

$or = $qb->expr()->orX();
$or->add($qb->expr()->eq('u.id', 1));
$or->add($qb->expr()->eq('u.id', 2));

$qb->update('User', 'u')
    ->set('u.password', '?')
    ->where($or);
Parameters
$predicates : mixed

The restriction predicates.

Return values
$this

findRootAlias()

Finds the root entity alias of the joined entity.

private findRootAlias(string $alias, string $parentAlias) : string
Parameters
$alias : string

The alias of the new join entity

$parentAlias : string

The parent entity alias of the join relationship

Return values
string

getDQLForDelete()

private getDQLForDelete() : string
Return values
string

getDQLForSelect()

private getDQLForSelect() : string
Return values
string

getDQLForUpdate()

private getDQLForUpdate() : string
Return values
string

getReducedDQLQueryPart()

private getReducedDQLQueryPart(string $queryPartName[, array<string|int, mixed> $options = [] ]) : string
Parameters
$queryPartName : string
$options : array<string|int, mixed> = []
Tags
psalm-param

array<string, mixed> $options

Return values
string

        
On this page

Search results