QueryBuilder.php 35KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182
  1. <?php
  2. /*
  3. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  4. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  5. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  6. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  7. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  8. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  9. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  10. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  11. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  12. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  13. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  14. *
  15. * This software consists of voluntary contributions made by many individuals
  16. * and is licensed under the MIT license. For more information, see
  17. * <http://www.doctrine-project.org>.
  18. */
  19. namespace Doctrine\ORM;
  20. use Doctrine\Common\Collections\ArrayCollection;
  21. use Doctrine\ORM\Query\Expr;
  22. /**
  23. * This class is responsible for building DQL query strings via an object oriented
  24. * PHP interface.
  25. *
  26. * @since 2.0
  27. * @author Guilherme Blanco <guilhermeblanco@hotmail.com>
  28. * @author Jonathan Wage <jonwage@gmail.com>
  29. * @author Roman Borschel <roman@code-factory.org>
  30. */
  31. class QueryBuilder
  32. {
  33. /* The query types. */
  34. const SELECT = 0;
  35. const DELETE = 1;
  36. const UPDATE = 2;
  37. /** The builder states. */
  38. const STATE_DIRTY = 0;
  39. const STATE_CLEAN = 1;
  40. /**
  41. * @var EntityManager The EntityManager used by this QueryBuilder.
  42. */
  43. private $_em;
  44. /**
  45. * @var array The array of DQL parts collected.
  46. */
  47. private $_dqlParts = array(
  48. 'distinct' => false,
  49. 'select' => array(),
  50. 'from' => array(),
  51. 'join' => array(),
  52. 'set' => array(),
  53. 'where' => null,
  54. 'groupBy' => array(),
  55. 'having' => null,
  56. 'orderBy' => array()
  57. );
  58. /**
  59. * @var integer The type of query this is. Can be select, update or delete.
  60. */
  61. private $_type = self::SELECT;
  62. /**
  63. * @var integer The state of the query object. Can be dirty or clean.
  64. */
  65. private $_state = self::STATE_CLEAN;
  66. /**
  67. * @var string The complete DQL string for this query.
  68. */
  69. private $_dql;
  70. /**
  71. * @var \Doctrine\Common\Collections\ArrayCollection The query parameters.
  72. */
  73. private $parameters = array();
  74. /**
  75. * @var integer The index of the first result to retrieve.
  76. */
  77. private $_firstResult = null;
  78. /**
  79. * @var integer The maximum number of results to retrieve.
  80. */
  81. private $_maxResults = null;
  82. /**
  83. * @var array Keeps root entity alias names for join entities.
  84. */
  85. private $joinRootAliases = array();
  86. /**
  87. * Initializes a new <tt>QueryBuilder</tt> that uses the given <tt>EntityManager</tt>.
  88. *
  89. * @param EntityManager $em The EntityManager to use.
  90. */
  91. public function __construct(EntityManager $em)
  92. {
  93. $this->_em = $em;
  94. $this->parameters = new ArrayCollection();
  95. }
  96. /**
  97. * Gets an ExpressionBuilder used for object-oriented construction of query expressions.
  98. * This producer method is intended for convenient inline usage. Example:
  99. *
  100. * <code>
  101. * $qb = $em->createQueryBuilder()
  102. * ->select('u')
  103. * ->from('User', 'u')
  104. * ->where($qb->expr()->eq('u.id', 1));
  105. * </code>
  106. *
  107. * For more complex expression construction, consider storing the expression
  108. * builder object in a local variable.
  109. *
  110. * @return Query\Expr
  111. */
  112. public function expr()
  113. {
  114. return $this->_em->getExpressionBuilder();
  115. }
  116. /**
  117. * Get the type of the currently built query.
  118. *
  119. * @return integer
  120. */
  121. public function getType()
  122. {
  123. return $this->_type;
  124. }
  125. /**
  126. * Get the associated EntityManager for this query builder.
  127. *
  128. * @return EntityManager
  129. */
  130. public function getEntityManager()
  131. {
  132. return $this->_em;
  133. }
  134. /**
  135. * Get the state of this query builder instance.
  136. *
  137. * @return integer Either QueryBuilder::STATE_DIRTY or QueryBuilder::STATE_CLEAN.
  138. */
  139. public function getState()
  140. {
  141. return $this->_state;
  142. }
  143. /**
  144. * Get the complete DQL string formed by the current specifications of this QueryBuilder.
  145. *
  146. * <code>
  147. * $qb = $em->createQueryBuilder()
  148. * ->select('u')
  149. * ->from('User', 'u')
  150. * echo $qb->getDql(); // SELECT u FROM User u
  151. * </code>
  152. *
  153. * @return string The DQL query string.
  154. */
  155. public function getDQL()
  156. {
  157. if ($this->_dql !== null && $this->_state === self::STATE_CLEAN) {
  158. return $this->_dql;
  159. }
  160. $dql = '';
  161. switch ($this->_type) {
  162. case self::DELETE:
  163. $dql = $this->_getDQLForDelete();
  164. break;
  165. case self::UPDATE:
  166. $dql = $this->_getDQLForUpdate();
  167. break;
  168. case self::SELECT:
  169. default:
  170. $dql = $this->_getDQLForSelect();
  171. break;
  172. }
  173. $this->_state = self::STATE_CLEAN;
  174. $this->_dql = $dql;
  175. return $dql;
  176. }
  177. /**
  178. * Constructs a Query instance from the current specifications of the builder.
  179. *
  180. * <code>
  181. * $qb = $em->createQueryBuilder()
  182. * ->select('u')
  183. * ->from('User', 'u');
  184. * $q = $qb->getQuery();
  185. * $results = $q->execute();
  186. * </code>
  187. *
  188. * @return Query
  189. */
  190. public function getQuery()
  191. {
  192. $parameters = clone $this->parameters;
  193. return $this->_em->createQuery($this->getDQL())
  194. ->setParameters($parameters)
  195. ->setFirstResult($this->_firstResult)
  196. ->setMaxResults($this->_maxResults);
  197. }
  198. /**
  199. * Finds the root entity alias of the joined entity.
  200. *
  201. * @param string $alias The alias of the new join entity
  202. * @param string $parentAlias The parent entity alias of the join relationship
  203. * @return string
  204. */
  205. private function findRootAlias($alias, $parentAlias)
  206. {
  207. $rootAlias = null;
  208. if (in_array($parentAlias, $this->getRootAliases())) {
  209. $rootAlias = $parentAlias;
  210. } elseif (isset($this->joinRootAliases[$parentAlias])) {
  211. $rootAlias = $this->joinRootAliases[$parentAlias];
  212. } else {
  213. // Should never happen with correct joining order. Might be
  214. // thoughtful to throw exception instead.
  215. $rootAlias = $this->getRootAlias();
  216. }
  217. $this->joinRootAliases[$alias] = $rootAlias;
  218. return $rootAlias;
  219. }
  220. /**
  221. * Gets the FIRST root alias of the query. This is the first entity alias involved
  222. * in the construction of the query.
  223. *
  224. * <code>
  225. * $qb = $em->createQueryBuilder()
  226. * ->select('u')
  227. * ->from('User', 'u');
  228. *
  229. * echo $qb->getRootAlias(); // u
  230. * </code>
  231. *
  232. * @deprecated Please use $qb->getRootAliases() instead.
  233. * @return string $rootAlias
  234. */
  235. public function getRootAlias()
  236. {
  237. $aliases = $this->getRootAliases();
  238. return $aliases[0];
  239. }
  240. /**
  241. * Gets the root aliases of the query. This is the entity aliases involved
  242. * in the construction of the query.
  243. *
  244. * <code>
  245. * $qb = $em->createQueryBuilder()
  246. * ->select('u')
  247. * ->from('User', 'u');
  248. *
  249. * $qb->getRootAliases(); // array('u')
  250. * </code>
  251. *
  252. * @return array $rootAliases
  253. */
  254. public function getRootAliases()
  255. {
  256. $aliases = array();
  257. foreach ($this->_dqlParts['from'] as &$fromClause) {
  258. if (is_string($fromClause)) {
  259. $spacePos = strrpos($fromClause, ' ');
  260. $from = substr($fromClause, 0, $spacePos);
  261. $alias = substr($fromClause, $spacePos + 1);
  262. $fromClause = new Query\Expr\From($from, $alias);
  263. }
  264. $aliases[] = $fromClause->getAlias();
  265. }
  266. return $aliases;
  267. }
  268. /**
  269. * Gets the root entities of the query. This is the entity aliases involved
  270. * in the construction of the query.
  271. *
  272. * <code>
  273. * $qb = $em->createQueryBuilder()
  274. * ->select('u')
  275. * ->from('User', 'u');
  276. *
  277. * $qb->getRootEntities(); // array('User')
  278. * </code>
  279. *
  280. * @return array $rootEntities
  281. */
  282. public function getRootEntities()
  283. {
  284. $entities = array();
  285. foreach ($this->_dqlParts['from'] as &$fromClause) {
  286. if (is_string($fromClause)) {
  287. $spacePos = strrpos($fromClause, ' ');
  288. $from = substr($fromClause, 0, $spacePos);
  289. $alias = substr($fromClause, $spacePos + 1);
  290. $fromClause = new Query\Expr\From($from, $alias);
  291. }
  292. $entities[] = $fromClause->getFrom();
  293. }
  294. return $entities;
  295. }
  296. /**
  297. * Sets a query parameter for the query being constructed.
  298. *
  299. * <code>
  300. * $qb = $em->createQueryBuilder()
  301. * ->select('u')
  302. * ->from('User', 'u')
  303. * ->where('u.id = :user_id')
  304. * ->setParameter('user_id', 1);
  305. * </code>
  306. *
  307. * @param string|integer $key The parameter position or name.
  308. * @param mixed $value The parameter value.
  309. * @param string|null $type PDO::PARAM_* or \Doctrine\DBAL\Types\Type::* constant
  310. * @return QueryBuilder This QueryBuilder instance.
  311. */
  312. public function setParameter($key, $value, $type = null)
  313. {
  314. $filteredParameters = $this->parameters->filter(
  315. function ($parameter) use ($key)
  316. {
  317. // Must not be identical because of string to integer conversion
  318. return ($key == $parameter->getName());
  319. }
  320. );
  321. if (count($filteredParameters)) {
  322. $parameter = $filteredParameters->first();
  323. $parameter->setValue($value, $type);
  324. return $this;
  325. }
  326. $parameter = new Query\Parameter($key, $value, $type);
  327. $this->parameters->add($parameter);
  328. return $this;
  329. }
  330. /**
  331. * Sets a collection of query parameters for the query being constructed.
  332. *
  333. * <code>
  334. * $qb = $em->createQueryBuilder()
  335. * ->select('u')
  336. * ->from('User', 'u')
  337. * ->where('u.id = :user_id1 OR u.id = :user_id2')
  338. * ->setParameters(new ArrayCollection(array(
  339. * new Parameter('user_id1', 1),
  340. * new Parameter('user_id2', 2)
  341. )));
  342. * </code>
  343. *
  344. * @param \Doctrine\Common\Collections\ArrayCollection|array $params The query parameters to set.
  345. * @return QueryBuilder This QueryBuilder instance.
  346. */
  347. public function setParameters($parameters)
  348. {
  349. // BC compatibility with 2.3-
  350. if (is_array($parameters)) {
  351. $parameterCollection = new ArrayCollection();
  352. foreach ($parameters as $key => $value) {
  353. $parameter = new Query\Parameter($key, $value);
  354. $parameterCollection->add($parameter);
  355. }
  356. $parameters = $parameterCollection;
  357. }
  358. $this->parameters = $parameters;
  359. return $this;
  360. }
  361. /**
  362. * Gets all defined query parameters for the query being constructed.
  363. *
  364. * @return \Doctrine\Common\Collections\ArrayCollection The currently defined query parameters.
  365. */
  366. public function getParameters()
  367. {
  368. return $this->parameters;
  369. }
  370. /**
  371. * Gets a (previously set) query parameter of the query being constructed.
  372. *
  373. * @param mixed $key The key (index or name) of the bound parameter.
  374. *
  375. * @return Query\Parameter|null The value of the bound parameter.
  376. */
  377. public function getParameter($key)
  378. {
  379. $filteredParameters = $this->parameters->filter(
  380. function ($parameter) use ($key)
  381. {
  382. // Must not be identical because of string to integer conversion
  383. return ($key == $parameter->getName());
  384. }
  385. );
  386. return count($filteredParameters) ? $filteredParameters->first() : null;
  387. }
  388. /**
  389. * Sets the position of the first result to retrieve (the "offset").
  390. *
  391. * @param integer $firstResult The first result to return.
  392. * @return QueryBuilder This QueryBuilder instance.
  393. */
  394. public function setFirstResult($firstResult)
  395. {
  396. $this->_firstResult = $firstResult;
  397. return $this;
  398. }
  399. /**
  400. * Gets the position of the first result the query object was set to retrieve (the "offset").
  401. * Returns NULL if {@link setFirstResult} was not applied to this QueryBuilder.
  402. *
  403. * @return integer The position of the first result.
  404. */
  405. public function getFirstResult()
  406. {
  407. return $this->_firstResult;
  408. }
  409. /**
  410. * Sets the maximum number of results to retrieve (the "limit").
  411. *
  412. * @param integer $maxResults The maximum number of results to retrieve.
  413. * @return QueryBuilder This QueryBuilder instance.
  414. */
  415. public function setMaxResults($maxResults)
  416. {
  417. $this->_maxResults = $maxResults;
  418. return $this;
  419. }
  420. /**
  421. * Gets the maximum number of results the query object was set to retrieve (the "limit").
  422. * Returns NULL if {@link setMaxResults} was not applied to this query builder.
  423. *
  424. * @return integer Maximum number of results.
  425. */
  426. public function getMaxResults()
  427. {
  428. return $this->_maxResults;
  429. }
  430. /**
  431. * Either appends to or replaces a single, generic query part.
  432. *
  433. * The available parts are: 'select', 'from', 'join', 'set', 'where',
  434. * 'groupBy', 'having' and 'orderBy'.
  435. *
  436. * @param string $dqlPartName
  437. * @param string $dqlPart
  438. * @param string $append
  439. * @return QueryBuilder This QueryBuilder instance.
  440. */
  441. public function add($dqlPartName, $dqlPart, $append = false)
  442. {
  443. $isMultiple = is_array($this->_dqlParts[$dqlPartName]);
  444. // This is introduced for backwards compatibility reasons.
  445. // TODO: Remove for 3.0
  446. if ($dqlPartName == 'join') {
  447. $newDqlPart = array();
  448. foreach ($dqlPart as $k => $v) {
  449. $k = is_numeric($k) ? $this->getRootAlias() : $k;
  450. $newDqlPart[$k] = $v;
  451. }
  452. $dqlPart = $newDqlPart;
  453. }
  454. if ($append && $isMultiple) {
  455. if (is_array($dqlPart)) {
  456. $key = key($dqlPart);
  457. $this->_dqlParts[$dqlPartName][$key][] = $dqlPart[$key];
  458. } else {
  459. $this->_dqlParts[$dqlPartName][] = $dqlPart;
  460. }
  461. } else {
  462. $this->_dqlParts[$dqlPartName] = ($isMultiple) ? array($dqlPart) : $dqlPart;
  463. }
  464. $this->_state = self::STATE_DIRTY;
  465. return $this;
  466. }
  467. /**
  468. * Specifies an item that is to be returned in the query result.
  469. * Replaces any previously specified selections, if any.
  470. *
  471. * <code>
  472. * $qb = $em->createQueryBuilder()
  473. * ->select('u', 'p')
  474. * ->from('User', 'u')
  475. * ->leftJoin('u.Phonenumbers', 'p');
  476. * </code>
  477. *
  478. * @param mixed $select The selection expressions.
  479. * @return QueryBuilder This QueryBuilder instance.
  480. */
  481. public function select($select = null)
  482. {
  483. $this->_type = self::SELECT;
  484. if (empty($select)) {
  485. return $this;
  486. }
  487. $selects = is_array($select) ? $select : func_get_args();
  488. return $this->add('select', new Expr\Select($selects), false);
  489. }
  490. /**
  491. * Add a DISTINCT flag to this query.
  492. *
  493. * <code>
  494. * $qb = $em->createQueryBuilder()
  495. * ->select('u')
  496. * ->distinct()
  497. * ->from('User', 'u');
  498. * </code>
  499. *
  500. * @param bool
  501. * @return QueryBuilder
  502. */
  503. public function distinct($flag = true)
  504. {
  505. $this->_dqlParts['distinct'] = (bool) $flag;
  506. return $this;
  507. }
  508. /**
  509. * Adds an item that is to be returned in the query result.
  510. *
  511. * <code>
  512. * $qb = $em->createQueryBuilder()
  513. * ->select('u')
  514. * ->addSelect('p')
  515. * ->from('User', 'u')
  516. * ->leftJoin('u.Phonenumbers', 'p');
  517. * </code>
  518. *
  519. * @param mixed $select The selection expression.
  520. * @return QueryBuilder This QueryBuilder instance.
  521. */
  522. public function addSelect($select = null)
  523. {
  524. $this->_type = self::SELECT;
  525. if (empty($select)) {
  526. return $this;
  527. }
  528. $selects = is_array($select) ? $select : func_get_args();
  529. return $this->add('select', new Expr\Select($selects), true);
  530. }
  531. /**
  532. * Turns the query being built into a bulk delete query that ranges over
  533. * a certain entity type.
  534. *
  535. * <code>
  536. * $qb = $em->createQueryBuilder()
  537. * ->delete('User', 'u')
  538. * ->where('u.id = :user_id');
  539. * ->setParameter('user_id', 1);
  540. * </code>
  541. *
  542. * @param string $delete The class/type whose instances are subject to the deletion.
  543. * @param string $alias The class/type alias used in the constructed query.
  544. * @return QueryBuilder This QueryBuilder instance.
  545. */
  546. public function delete($delete = null, $alias = null)
  547. {
  548. $this->_type = self::DELETE;
  549. if ( ! $delete) {
  550. return $this;
  551. }
  552. return $this->add('from', new Expr\From($delete, $alias));
  553. }
  554. /**
  555. * Turns the query being built into a bulk update query that ranges over
  556. * a certain entity type.
  557. *
  558. * <code>
  559. * $qb = $em->createQueryBuilder()
  560. * ->update('User', 'u')
  561. * ->set('u.password', md5('password'))
  562. * ->where('u.id = ?');
  563. * </code>
  564. *
  565. * @param string $update The class/type whose instances are subject to the update.
  566. * @param string $alias The class/type alias used in the constructed query.
  567. * @return QueryBuilder This QueryBuilder instance.
  568. */
  569. public function update($update = null, $alias = null)
  570. {
  571. $this->_type = self::UPDATE;
  572. if ( ! $update) {
  573. return $this;
  574. }
  575. return $this->add('from', new Expr\From($update, $alias));
  576. }
  577. /**
  578. * Create and add a query root corresponding to the entity identified by the given alias,
  579. * forming a cartesian product with any existing query roots.
  580. *
  581. * <code>
  582. * $qb = $em->createQueryBuilder()
  583. * ->select('u')
  584. * ->from('User', 'u')
  585. * </code>
  586. *
  587. * @param string $from The class name.
  588. * @param string $alias The alias of the class.
  589. * @param string $indexBy The index for the from.
  590. * @return QueryBuilder This QueryBuilder instance.
  591. */
  592. public function from($from, $alias, $indexBy = null)
  593. {
  594. return $this->add('from', new Expr\From($from, $alias, $indexBy), true);
  595. }
  596. /**
  597. * Creates and adds a join over an entity association to the query.
  598. *
  599. * The entities in the joined association will be fetched as part of the query
  600. * result if the alias used for the joined association is placed in the select
  601. * expressions.
  602. *
  603. * <code>
  604. * $qb = $em->createQueryBuilder()
  605. * ->select('u')
  606. * ->from('User', 'u')
  607. * ->join('u.Phonenumbers', 'p', Expr\Join::WITH, 'p.is_primary = 1');
  608. * </code>
  609. *
  610. * @param string $join The relationship to join
  611. * @param string $alias The alias of the join
  612. * @param string $conditionType The condition type constant. Either ON or WITH.
  613. * @param string $condition The condition for the join
  614. * @param string $indexBy The index for the join
  615. * @return QueryBuilder This QueryBuilder instance.
  616. */
  617. public function join($join, $alias, $conditionType = null, $condition = null, $indexBy = null)
  618. {
  619. return $this->innerJoin($join, $alias, $conditionType, $condition, $indexBy);
  620. }
  621. /**
  622. * Creates and adds a join over an entity association to the query.
  623. *
  624. * The entities in the joined association will be fetched as part of the query
  625. * result if the alias used for the joined association is placed in the select
  626. * expressions.
  627. *
  628. * [php]
  629. * $qb = $em->createQueryBuilder()
  630. * ->select('u')
  631. * ->from('User', 'u')
  632. * ->innerJoin('u.Phonenumbers', 'p', Expr\Join::WITH, 'p.is_primary = 1');
  633. *
  634. * @param string $join The relationship to join
  635. * @param string $alias The alias of the join
  636. * @param string $conditionType The condition type constant. Either ON or WITH.
  637. * @param string $condition The condition for the join
  638. * @param string $indexBy The index for the join
  639. * @return QueryBuilder This QueryBuilder instance.
  640. */
  641. public function innerJoin($join, $alias, $conditionType = null, $condition = null, $indexBy = null)
  642. {
  643. $parentAlias = substr($join, 0, strpos($join, '.'));
  644. $rootAlias = $this->findRootAlias($alias, $parentAlias);
  645. $join = new Expr\Join(
  646. Expr\Join::INNER_JOIN, $join, $alias, $conditionType, $condition, $indexBy
  647. );
  648. return $this->add('join', array($rootAlias => $join), true);
  649. }
  650. /**
  651. * Creates and adds a left join over an entity association to the query.
  652. *
  653. * The entities in the joined association will be fetched as part of the query
  654. * result if the alias used for the joined association is placed in the select
  655. * expressions.
  656. *
  657. * <code>
  658. * $qb = $em->createQueryBuilder()
  659. * ->select('u')
  660. * ->from('User', 'u')
  661. * ->leftJoin('u.Phonenumbers', 'p', Expr\Join::WITH, 'p.is_primary = 1');
  662. * </code>
  663. *
  664. * @param string $join The relationship to join
  665. * @param string $alias The alias of the join
  666. * @param string $conditionType The condition type constant. Either ON or WITH.
  667. * @param string $condition The condition for the join
  668. * @param string $indexBy The index for the join
  669. * @return QueryBuilder This QueryBuilder instance.
  670. */
  671. public function leftJoin($join, $alias, $conditionType = null, $condition = null, $indexBy = null)
  672. {
  673. $parentAlias = substr($join, 0, strpos($join, '.'));
  674. $rootAlias = $this->findRootAlias($alias, $parentAlias);
  675. $join = new Expr\Join(
  676. Expr\Join::LEFT_JOIN, $join, $alias, $conditionType, $condition, $indexBy
  677. );
  678. return $this->add('join', array($rootAlias => $join), true);
  679. }
  680. /**
  681. * Sets a new value for a field in a bulk update query.
  682. *
  683. * <code>
  684. * $qb = $em->createQueryBuilder()
  685. * ->update('User', 'u')
  686. * ->set('u.password', md5('password'))
  687. * ->where('u.id = ?');
  688. * </code>
  689. *
  690. * @param string $key The key/field to set.
  691. * @param string $value The value, expression, placeholder, etc.
  692. * @return QueryBuilder This QueryBuilder instance.
  693. */
  694. public function set($key, $value)
  695. {
  696. return $this->add('set', new Expr\Comparison($key, Expr\Comparison::EQ, $value), true);
  697. }
  698. /**
  699. * Specifies one or more restrictions to the query result.
  700. * Replaces any previously specified restrictions, if any.
  701. *
  702. * <code>
  703. * $qb = $em->createQueryBuilder()
  704. * ->select('u')
  705. * ->from('User', 'u')
  706. * ->where('u.id = ?');
  707. *
  708. * // You can optionally programatically build and/or expressions
  709. * $qb = $em->createQueryBuilder();
  710. *
  711. * $or = $qb->expr()->orx();
  712. * $or->add($qb->expr()->eq('u.id', 1));
  713. * $or->add($qb->expr()->eq('u.id', 2));
  714. *
  715. * $qb->update('User', 'u')
  716. * ->set('u.password', md5('password'))
  717. * ->where($or);
  718. * </code>
  719. *
  720. * @param mixed $predicates The restriction predicates.
  721. * @return QueryBuilder This QueryBuilder instance.
  722. */
  723. public function where($predicates)
  724. {
  725. if ( ! (func_num_args() == 1 && $predicates instanceof Expr\Composite)) {
  726. $predicates = new Expr\Andx(func_get_args());
  727. }
  728. return $this->add('where', $predicates);
  729. }
  730. /**
  731. * Adds one or more restrictions to the query results, forming a logical
  732. * conjunction with any previously specified restrictions.
  733. *
  734. * <code>
  735. * $qb = $em->createQueryBuilder()
  736. * ->select('u')
  737. * ->from('User', 'u')
  738. * ->where('u.username LIKE ?')
  739. * ->andWhere('u.is_active = 1');
  740. * </code>
  741. *
  742. * @param mixed $where The query restrictions.
  743. * @return QueryBuilder This QueryBuilder instance.
  744. * @see where()
  745. */
  746. public function andWhere($where)
  747. {
  748. $where = $this->getDQLPart('where');
  749. $args = func_get_args();
  750. if ($where instanceof Expr\Andx) {
  751. $where->addMultiple($args);
  752. } else {
  753. array_unshift($args, $where);
  754. $where = new Expr\Andx($args);
  755. }
  756. return $this->add('where', $where, true);
  757. }
  758. /**
  759. * Adds one or more restrictions to the query results, forming a logical
  760. * disjunction with any previously specified restrictions.
  761. *
  762. * <code>
  763. * $qb = $em->createQueryBuilder()
  764. * ->select('u')
  765. * ->from('User', 'u')
  766. * ->where('u.id = 1')
  767. * ->orWhere('u.id = 2');
  768. * </code>
  769. *
  770. * @param mixed $where The WHERE statement
  771. * @return QueryBuilder $qb
  772. * @see where()
  773. */
  774. public function orWhere($where)
  775. {
  776. $where = $this->getDqlPart('where');
  777. $args = func_get_args();
  778. if ($where instanceof Expr\Orx) {
  779. $where->addMultiple($args);
  780. } else {
  781. array_unshift($args, $where);
  782. $where = new Expr\Orx($args);
  783. }
  784. return $this->add('where', $where, true);
  785. }
  786. /**
  787. * Specifies a grouping over the results of the query.
  788. * Replaces any previously specified groupings, if any.
  789. *
  790. * <code>
  791. * $qb = $em->createQueryBuilder()
  792. * ->select('u')
  793. * ->from('User', 'u')
  794. * ->groupBy('u.id');
  795. * </code>
  796. *
  797. * @param string $groupBy The grouping expression.
  798. * @return QueryBuilder This QueryBuilder instance.
  799. */
  800. public function groupBy($groupBy)
  801. {
  802. return $this->add('groupBy', new Expr\GroupBy(func_get_args()));
  803. }
  804. /**
  805. * Adds a grouping expression to the query.
  806. *
  807. * <code>
  808. * $qb = $em->createQueryBuilder()
  809. * ->select('u')
  810. * ->from('User', 'u')
  811. * ->groupBy('u.lastLogin');
  812. * ->addGroupBy('u.createdAt')
  813. * </code>
  814. *
  815. * @param string $groupBy The grouping expression.
  816. * @return QueryBuilder This QueryBuilder instance.
  817. */
  818. public function addGroupBy($groupBy)
  819. {
  820. return $this->add('groupBy', new Expr\GroupBy(func_get_args()), true);
  821. }
  822. /**
  823. * Specifies a restriction over the groups of the query.
  824. * Replaces any previous having restrictions, if any.
  825. *
  826. * @param mixed $having The restriction over the groups.
  827. * @return QueryBuilder This QueryBuilder instance.
  828. */
  829. public function having($having)
  830. {
  831. if ( ! (func_num_args() == 1 && ($having instanceof Expr\Andx || $having instanceof Expr\Orx))) {
  832. $having = new Expr\Andx(func_get_args());
  833. }
  834. return $this->add('having', $having);
  835. }
  836. /**
  837. * Adds a restriction over the groups of the query, forming a logical
  838. * conjunction with any existing having restrictions.
  839. *
  840. * @param mixed $having The restriction to append.
  841. * @return QueryBuilder This QueryBuilder instance.
  842. */
  843. public function andHaving($having)
  844. {
  845. $having = $this->getDqlPart('having');
  846. $args = func_get_args();
  847. if ($having instanceof Expr\Andx) {
  848. $having->addMultiple($args);
  849. } else {
  850. array_unshift($args, $having);
  851. $having = new Expr\Andx($args);
  852. }
  853. return $this->add('having', $having);
  854. }
  855. /**
  856. * Adds a restriction over the groups of the query, forming a logical
  857. * disjunction with any existing having restrictions.
  858. *
  859. * @param mixed $having The restriction to add.
  860. * @return QueryBuilder This QueryBuilder instance.
  861. */
  862. public function orHaving($having)
  863. {
  864. $having = $this->getDqlPart('having');
  865. $args = func_get_args();
  866. if ($having instanceof Expr\Orx) {
  867. $having->addMultiple($args);
  868. } else {
  869. array_unshift($args, $having);
  870. $having = new Expr\Orx($args);
  871. }
  872. return $this->add('having', $having);
  873. }
  874. /**
  875. * Specifies an ordering for the query results.
  876. * Replaces any previously specified orderings, if any.
  877. *
  878. * @param string $sort The ordering expression.
  879. * @param string $order The ordering direction.
  880. * @return QueryBuilder This QueryBuilder instance.
  881. */
  882. public function orderBy($sort, $order = null)
  883. {
  884. $orderBy = ($sort instanceof Expr\OrderBy) ? $sort : new Expr\OrderBy($sort, $order);
  885. return $this->add('orderBy', $orderBy);
  886. }
  887. /**
  888. * Adds an ordering to the query results.
  889. *
  890. * @param string $sort The ordering expression.
  891. * @param string $order The ordering direction.
  892. * @return QueryBuilder This QueryBuilder instance.
  893. */
  894. public function addOrderBy($sort, $order = null)
  895. {
  896. return $this->add('orderBy', new Expr\OrderBy($sort, $order), true);
  897. }
  898. /**
  899. * Get a query part by its name.
  900. *
  901. * @param string $queryPartName
  902. * @return mixed $queryPart
  903. * @todo Rename: getQueryPart (or remove?)
  904. */
  905. public function getDQLPart($queryPartName)
  906. {
  907. return $this->_dqlParts[$queryPartName];
  908. }
  909. /**
  910. * Get all query parts.
  911. *
  912. * @return array $dqlParts
  913. * @todo Rename: getQueryParts (or remove?)
  914. */
  915. public function getDQLParts()
  916. {
  917. return $this->_dqlParts;
  918. }
  919. private function _getDQLForDelete()
  920. {
  921. return 'DELETE'
  922. . $this->_getReducedDQLQueryPart('from', array('pre' => ' ', 'separator' => ', '))
  923. . $this->_getReducedDQLQueryPart('where', array('pre' => ' WHERE '))
  924. . $this->_getReducedDQLQueryPart('orderBy', array('pre' => ' ORDER BY ', 'separator' => ', '));
  925. }
  926. private function _getDQLForUpdate()
  927. {
  928. return 'UPDATE'
  929. . $this->_getReducedDQLQueryPart('from', array('pre' => ' ', 'separator' => ', '))
  930. . $this->_getReducedDQLQueryPart('set', array('pre' => ' SET ', 'separator' => ', '))
  931. . $this->_getReducedDQLQueryPart('where', array('pre' => ' WHERE '))
  932. . $this->_getReducedDQLQueryPart('orderBy', array('pre' => ' ORDER BY ', 'separator' => ', '));
  933. }
  934. private function _getDQLForSelect()
  935. {
  936. $dql = 'SELECT'
  937. . ($this->_dqlParts['distinct']===true ? ' DISTINCT' : '')
  938. . $this->_getReducedDQLQueryPart('select', array('pre' => ' ', 'separator' => ', '));
  939. $fromParts = $this->getDQLPart('from');
  940. $joinParts = $this->getDQLPart('join');
  941. $fromClauses = array();
  942. // Loop through all FROM clauses
  943. if ( ! empty($fromParts)) {
  944. $dql .= ' FROM ';
  945. foreach ($fromParts as $from) {
  946. $fromClause = (string) $from;
  947. if ($from instanceof Expr\From && isset($joinParts[$from->getAlias()])) {
  948. foreach ($joinParts[$from->getAlias()] as $join) {
  949. $fromClause .= ' ' . ((string) $join);
  950. }
  951. }
  952. $fromClauses[] = $fromClause;
  953. }
  954. }
  955. $dql .= implode(', ', $fromClauses)
  956. . $this->_getReducedDQLQueryPart('where', array('pre' => ' WHERE '))
  957. . $this->_getReducedDQLQueryPart('groupBy', array('pre' => ' GROUP BY ', 'separator' => ', '))
  958. . $this->_getReducedDQLQueryPart('having', array('pre' => ' HAVING '))
  959. . $this->_getReducedDQLQueryPart('orderBy', array('pre' => ' ORDER BY ', 'separator' => ', '));
  960. return $dql;
  961. }
  962. private function _getReducedDQLQueryPart($queryPartName, $options = array())
  963. {
  964. $queryPart = $this->getDQLPart($queryPartName);
  965. if (empty($queryPart)) {
  966. return (isset($options['empty']) ? $options['empty'] : '');
  967. }
  968. return (isset($options['pre']) ? $options['pre'] : '')
  969. . (is_array($queryPart) ? implode($options['separator'], $queryPart) : $queryPart)
  970. . (isset($options['post']) ? $options['post'] : '');
  971. }
  972. /**
  973. * Reset DQL parts
  974. *
  975. * @param array $parts
  976. * @return QueryBuilder
  977. */
  978. public function resetDQLParts($parts = null)
  979. {
  980. if (is_null($parts)) {
  981. $parts = array_keys($this->_dqlParts);
  982. }
  983. foreach ($parts as $part) {
  984. $this->resetDQLPart($part);
  985. }
  986. return $this;
  987. }
  988. /**
  989. * Reset single DQL part
  990. *
  991. * @param string $part
  992. * @return QueryBuilder;
  993. */
  994. public function resetDQLPart($part)
  995. {
  996. $this->_dqlParts[$part] = is_array($this->_dqlParts[$part]) ? array() : null;
  997. $this->_state = self::STATE_DIRTY;
  998. return $this;
  999. }
  1000. /**
  1001. * Gets a string representation of this QueryBuilder which corresponds to
  1002. * the final DQL query being constructed.
  1003. *
  1004. * @return string The string representation of this QueryBuilder.
  1005. */
  1006. public function __toString()
  1007. {
  1008. return $this->getDQL();
  1009. }
  1010. /**
  1011. * Deep clone of all expression objects in the DQL parts.
  1012. *
  1013. * @return void
  1014. */
  1015. public function __clone()
  1016. {
  1017. foreach ($this->_dqlParts as $part => $elements) {
  1018. if (is_array($this->_dqlParts[$part])) {
  1019. foreach ($this->_dqlParts[$part] as $idx => $element) {
  1020. if (is_object($element)) {
  1021. $this->_dqlParts[$part][$idx] = clone $element;
  1022. }
  1023. }
  1024. } else if (is_object($elements)) {
  1025. $this->_dqlParts[$part] = clone $elements;
  1026. }
  1027. }
  1028. $parameters = array();
  1029. foreach ($this->parameters as $parameter) {
  1030. $parameters[] = clone $parameter;
  1031. }
  1032. $this->parameters = new ArrayCollection($parameters);
  1033. }
  1034. }