QueryBuilder.php 32KB

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