QueryBuilder.php 37 KB

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