Query.php 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  11. * @link https://cakephp.org CakePHP(tm) Project
  12. * @since 3.0.0
  13. * @license https://opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\ORM;
  16. use ArrayObject;
  17. use Cake\Database\ExpressionInterface;
  18. use Cake\Database\Query as DatabaseQuery;
  19. use Cake\Database\Schema\TableSchema;
  20. use Cake\Database\TypedResultInterface;
  21. use Cake\Database\TypeMap;
  22. use Cake\Database\ValueBinder;
  23. use Cake\Datasource\QueryInterface;
  24. use Cake\Datasource\QueryTrait;
  25. use JsonSerializable;
  26. use RuntimeException;
  27. /**
  28. * Extends the base Query class to provide new methods related to association
  29. * loading, automatic fields selection, automatic type casting and to wrap results
  30. * into a specific iterator that will be responsible for hydrating results if
  31. * required.
  32. *
  33. * @see \Cake\Collection\CollectionInterface For a full description of the collection methods supported by this class
  34. * @method \Cake\Collection\CollectionInterface each(callable $c) Passes each of the query results to the callable
  35. * @method \Cake\Collection\CollectionInterface filter(callable $c = null) Keeps the results using passing the callable test
  36. * @method \Cake\Collection\CollectionInterface reject(callable $c) Removes the results passing the callable test
  37. * @method bool every(callable $c) Returns true if all the results pass the callable test
  38. * @method bool some(callable $c) Returns true if at least one of the results pass the callable test
  39. * @method \Cake\Collection\CollectionInterface map(callable $c) Modifies each of the results using the callable
  40. * @method mixed reduce(callable $c, $zero = null) Folds all the results into a single value using the callable.
  41. * @method \Cake\Collection\CollectionInterface extract($field) Extracts a single column from each row
  42. * @method mixed max($field, $type = SORT_NUMERIC) Returns the maximum value for a single column in all the results.
  43. * @method mixed min($field, $type = SORT_NUMERIC) Returns the minimum value for a single column in all the results.
  44. * @method \Cake\Collection\CollectionInterface groupBy(string|callable $field) In-memory group all results by the value of a column.
  45. * @method \Cake\Collection\CollectionInterface indexBy(string|callable $field) Returns the results indexed by the value of a column.
  46. * @method int countBy(string|callable $field) Returns the number of unique values for a column
  47. * @method float sumOf(string|callable $field) Returns the sum of all values for a single column
  48. * @method \Cake\Collection\CollectionInterface shuffle() In-memory randomize the order the results are returned
  49. * @method \Cake\Collection\CollectionInterface sample($size = 10) In-memory shuffle the results and return a subset of them.
  50. * @method \Cake\Collection\CollectionInterface take($size = 1, $from = 0) In-memory limit and offset for the query results.
  51. * @method \Cake\Collection\CollectionInterface skip(int $howMany) Skips some rows from the start of the query result.
  52. * @method mixed last() Return the last row of the query result
  53. * @method \Cake\Collection\CollectionInterface append(array|\Traversable $items) Appends more rows to the result of the query.
  54. * @method \Cake\Collection\CollectionInterface combine($k, $v, $g = null) Returns the values of the column $v index by column $k,
  55. * and grouped by $g.
  56. * @method \Cake\Collection\CollectionInterface nest($k, $p, $n = 'children') Creates a tree structure by nesting the values of column $p into that
  57. * with the same value for $k using $n as the nesting key.
  58. * @method array toArray() Returns a key-value array with the results of this query.
  59. * @method array toList() Returns a numerically indexed array with the results of this query.
  60. * @method \Cake\Collection\CollectionInterface stopWhen(callable $c) Returns each row until the callable returns true.
  61. * @method \Cake\Collection\CollectionInterface zip(array|\Traversable $c) Returns the first result of both the query and $c in an array,
  62. * then the second results and so on.
  63. * @method \Cake\Collection\CollectionInterface zipWith($collections, callable $callable) Returns each of the results out of calling $c
  64. * with the first rows of the query and each of the items, then the second rows and so on.
  65. * @method \Cake\Collection\CollectionInterface chunk($size) Groups the results in arrays of $size rows each.
  66. * @method bool isEmpty() Returns true if this query found no results.
  67. * @mixin \Cake\Datasource\QueryTrait
  68. */
  69. class Query extends DatabaseQuery implements JsonSerializable, QueryInterface
  70. {
  71. use QueryTrait {
  72. cache as private _cache;
  73. all as private _all;
  74. _decorateResults as private _applyDecorators;
  75. __call as private _call;
  76. }
  77. /**
  78. * Indicates that the operation should append to the list
  79. *
  80. * @var int
  81. */
  82. const APPEND = 0;
  83. /**
  84. * Indicates that the operation should prepend to the list
  85. *
  86. * @var int
  87. */
  88. const PREPEND = 1;
  89. /**
  90. * Indicates that the operation should overwrite the list
  91. *
  92. * @var bool
  93. */
  94. const OVERWRITE = true;
  95. /**
  96. * Whether the user select any fields before being executed, this is used
  97. * to determined if any fields should be automatically be selected.
  98. *
  99. * @var bool
  100. */
  101. protected $_hasFields;
  102. /**
  103. * Tracks whether or not the original query should include
  104. * fields from the top level table.
  105. *
  106. * @var bool
  107. */
  108. protected $_autoFields;
  109. /**
  110. * Whether to hydrate results into entity objects
  111. *
  112. * @var bool
  113. */
  114. protected $_hydrate = true;
  115. /**
  116. * A callable function that can be used to calculate the total amount of
  117. * records this query will match when not using `limit`
  118. *
  119. * @var callable
  120. */
  121. protected $_counter;
  122. /**
  123. * Instance of a class responsible for storing association containments and
  124. * for eager loading them when this query is executed
  125. *
  126. * @var \Cake\ORM\EagerLoader
  127. */
  128. protected $_eagerLoader;
  129. /**
  130. * True if the beforeFind event has already been triggered for this query
  131. *
  132. * @var bool
  133. */
  134. protected $_beforeFindFired = false;
  135. /**
  136. * The COUNT(*) for the query.
  137. *
  138. * When set, count query execution will be bypassed.
  139. *
  140. * @var int|null
  141. */
  142. protected $_resultsCount;
  143. /**
  144. * Constructor
  145. *
  146. * @param \Cake\Database\Connection $connection The connection object
  147. * @param \Cake\ORM\Table $table The table this query is starting on
  148. */
  149. public function __construct($connection, $table)
  150. {
  151. parent::__construct($connection);
  152. $this->repository($table);
  153. if ($this->_repository) {
  154. $this->addDefaultTypes($this->_repository);
  155. }
  156. }
  157. /**
  158. * {@inheritDoc}
  159. *
  160. * If you pass an instance of a `Cake\ORM\Table` or `Cake\ORM\Association` class,
  161. * all the fields in the schema of the table or the association will be added to
  162. * the select clause.
  163. *
  164. * @param array|\Cake\Database\ExpressionInterface|string|\Cake\ORM\Table|\Cake\ORM\Association $fields fields
  165. * to be added to the list.
  166. * @param bool $overwrite whether to reset fields with passed list or not
  167. * @return $this
  168. */
  169. public function select($fields = [], $overwrite = false)
  170. {
  171. if ($fields instanceof Association) {
  172. $fields = $fields->getTarget();
  173. }
  174. if ($fields instanceof Table) {
  175. $fields = $this->aliasFields($fields->getSchema()->columns(), $fields->getAlias());
  176. }
  177. return parent::select($fields, $overwrite);
  178. }
  179. /**
  180. * Select all the columns associated to $table except the $excludedFields.
  181. * Excluded fields should not be aliased names.
  182. *
  183. *
  184. * @param Table|Association $table The table to use to get an array of columns
  185. * @param array $excludedFields The un-aliased column names you do not want selected from $table
  186. * @param bool $overwrite Whether to reset/remove previous selected fields
  187. * @return Query
  188. */
  189. public function selectAllExcept($table, array $excludedFields, $overwrite = false)
  190. {
  191. if ($table instanceof Association) {
  192. $table = $table->getTarget();
  193. }
  194. $aliasedFields = [];
  195. if ($table instanceof Table) {
  196. $fields = array_diff($table->getSchema()->columns(), $excludedFields);
  197. $aliasedFields = $this->aliasFields($fields);
  198. }
  199. return $this->select($aliasedFields, $overwrite);
  200. }
  201. /**
  202. * Hints this object to associate the correct types when casting conditions
  203. * for the database. This is done by extracting the field types from the schema
  204. * associated to the passed table object. This prevents the user from repeating
  205. * themselves when specifying conditions.
  206. *
  207. * This method returns the same query object for chaining.
  208. *
  209. * @param \Cake\ORM\Table $table The table to pull types from
  210. * @return $this
  211. */
  212. public function addDefaultTypes(Table $table)
  213. {
  214. $alias = $table->getAlias();
  215. $map = $table->getSchema()->typeMap();
  216. $fields = [];
  217. foreach ($map as $f => $type) {
  218. $fields[$f] = $fields[$alias . '.' . $f] = $fields[$alias . '__' . $f] = $type;
  219. }
  220. $this->getTypeMap()->addDefaults($fields);
  221. return $this;
  222. }
  223. /**
  224. * Sets the instance of the eager loader class to use for loading associations
  225. * and storing containments.
  226. *
  227. * @param \Cake\ORM\EagerLoader $instance The eager loader to use.
  228. * @return $this
  229. */
  230. public function setEagerLoader(EagerLoader $instance)
  231. {
  232. $this->_eagerLoader = $instance;
  233. return $this;
  234. }
  235. /**
  236. * Returns the currently configured instance.
  237. *
  238. * @return \Cake\ORM\EagerLoader
  239. */
  240. public function getEagerLoader()
  241. {
  242. if ($this->_eagerLoader === null) {
  243. $this->_eagerLoader = new EagerLoader();
  244. }
  245. return $this->_eagerLoader;
  246. }
  247. /**
  248. * Sets the instance of the eager loader class to use for loading associations
  249. * and storing containments. If called with no arguments, it will return the
  250. * currently configured instance.
  251. *
  252. * @deprecated 3.4.0 Use setEagerLoader()/getEagerLoader() instead.
  253. * @param \Cake\ORM\EagerLoader|null $instance The eager loader to use. Pass null
  254. * to get the current eagerloader.
  255. * @return \Cake\ORM\EagerLoader|$this
  256. */
  257. public function eagerLoader(EagerLoader $instance = null)
  258. {
  259. deprecationWarning(
  260. 'Query::eagerLoader() is deprecated. ' .
  261. 'Use setEagerLoader()/getEagerLoader() instead.'
  262. );
  263. if ($instance !== null) {
  264. return $this->setEagerLoader($instance);
  265. }
  266. return $this->getEagerLoader();
  267. }
  268. /**
  269. * Sets the list of associations that should be eagerly loaded along with this
  270. * query. The list of associated tables passed must have been previously set as
  271. * associations using the Table API.
  272. *
  273. * ### Example:
  274. *
  275. * ```
  276. * // Bring articles' author information
  277. * $query->contain('Author');
  278. *
  279. * // Also bring the category and tags associated to each article
  280. * $query->contain(['Category', 'Tag']);
  281. * ```
  282. *
  283. * Associations can be arbitrarily nested using dot notation or nested arrays,
  284. * this allows this object to calculate joins or any additional queries that
  285. * must be executed to bring the required associated data.
  286. *
  287. * ### Example:
  288. *
  289. * ```
  290. * // Eager load the product info, and for each product load other 2 associations
  291. * $query->contain(['Product' => ['Manufacturer', 'Distributor']);
  292. *
  293. * // Which is equivalent to calling
  294. * $query->contain(['Products.Manufactures', 'Products.Distributors']);
  295. *
  296. * // For an author query, load his region, state and country
  297. * $query->contain('Regions.States.Countries');
  298. * ```
  299. *
  300. * It is possible to control the conditions and fields selected for each of the
  301. * contained associations:
  302. *
  303. * ### Example:
  304. *
  305. * ```
  306. * $query->contain(['Tags' => function ($q) {
  307. * return $q->where(['Tags.is_popular' => true]);
  308. * }]);
  309. *
  310. * $query->contain(['Products.Manufactures' => function ($q) {
  311. * return $q->select(['name'])->where(['Manufactures.active' => true]);
  312. * }]);
  313. * ```
  314. *
  315. * Each association might define special options when eager loaded, the allowed
  316. * options that can be set per association are:
  317. *
  318. * - `foreignKey`: Used to set a different field to match both tables, if set to false
  319. * no join conditions will be generated automatically. `false` can only be used on
  320. * joinable associations and cannot be used with hasMany or belongsToMany associations.
  321. * - `fields`: An array with the fields that should be fetched from the association.
  322. * - `finder`: The finder to use when loading associated records. Either the name of the
  323. * finder as a string, or an array to define options to pass to the finder.
  324. * - `queryBuilder`: Equivalent to passing a callable instead of an options array.
  325. *
  326. * ### Example:
  327. *
  328. * ```
  329. * // Set options for the hasMany articles that will be eagerly loaded for an author
  330. * $query->contain([
  331. * 'Articles' => [
  332. * 'fields' => ['title', 'author_id']
  333. * ]
  334. * ]);
  335. * ```
  336. *
  337. * Finders can be configured to use options.
  338. *
  339. * ```
  340. * // Retrieve translations for the articles, but only those for the `en` and `es` locales
  341. * $query->contain([
  342. * 'Articles' => [
  343. * 'finder' => [
  344. * 'translations' => [
  345. * 'locales' => ['en', 'es']
  346. * ]
  347. * ]
  348. * ]
  349. * ]);
  350. * ```
  351. *
  352. * When containing associations, it is important to include foreign key columns.
  353. * Failing to do so will trigger exceptions.
  354. *
  355. * ```
  356. * // Use a query builder to add conditions to the containment
  357. * $query->contain('Authors', function ($q) {
  358. * return $q->where(...); // add conditions
  359. * });
  360. * // Use special join conditions for multiple containments in the same method call
  361. * $query->contain([
  362. * 'Authors' => [
  363. * 'foreignKey' => false,
  364. * 'queryBuilder' => function ($q) {
  365. * return $q->where(...); // Add full filtering conditions
  366. * }
  367. * ],
  368. * 'Tags' => function ($q) {
  369. * return $q->where(...); // add conditions
  370. * }
  371. * ]);
  372. * ```
  373. *
  374. * If called with no arguments, this function will return an array with
  375. * with the list of previously configured associations to be contained in the
  376. * result.
  377. *
  378. * If called with an empty first argument and `$override` is set to true, the
  379. * previous list will be emptied.
  380. *
  381. * @param array|string|null $associations List of table aliases to be queried.
  382. * @param callable|bool $override The query builder for the association, or
  383. * if associations is an array, a bool on whether to override previous list
  384. * with the one passed
  385. * defaults to merging previous list with the new one.
  386. * @return array|$this
  387. */
  388. public function contain($associations = null, $override = false)
  389. {
  390. $loader = $this->getEagerLoader();
  391. if ($override === true) {
  392. $this->clearContain();
  393. }
  394. if ($associations === null) {
  395. return $loader->contain();
  396. }
  397. $queryBuilder = null;
  398. if (is_callable($override)) {
  399. $queryBuilder = $override;
  400. }
  401. $result = $loader->contain($associations, $queryBuilder);
  402. $this->_addAssociationsToTypeMap($this->repository(), $this->getTypeMap(), $result);
  403. return $this;
  404. }
  405. /**
  406. * Clears the contained associations from the current query.
  407. *
  408. * @return $this
  409. */
  410. public function clearContain()
  411. {
  412. $this->getEagerLoader()->clearContain();
  413. $this->_dirty();
  414. return $this;
  415. }
  416. /**
  417. * Used to recursively add contained association column types to
  418. * the query.
  419. *
  420. * @param \Cake\ORM\Table $table The table instance to pluck associations from.
  421. * @param \Cake\Database\TypeMap $typeMap The typemap to check for columns in.
  422. * This typemap is indirectly mutated via Cake\ORM\Query::addDefaultTypes()
  423. * @param array $associations The nested tree of associations to walk.
  424. * @return void
  425. */
  426. protected function _addAssociationsToTypeMap($table, $typeMap, $associations)
  427. {
  428. foreach ($associations as $name => $nested) {
  429. if (!$table->hasAssociation($name)) {
  430. continue;
  431. }
  432. $association = $table->getAssociation($name);
  433. $target = $association->getTarget();
  434. $primary = (array)$target->getPrimaryKey();
  435. if (empty($primary) || $typeMap->type($target->aliasField($primary[0])) === null) {
  436. $this->addDefaultTypes($target);
  437. }
  438. if (!empty($nested)) {
  439. $this->_addAssociationsToTypeMap($target, $typeMap, $nested);
  440. }
  441. }
  442. }
  443. /**
  444. * Adds filtering conditions to this query to only bring rows that have a relation
  445. * to another from an associated table, based on conditions in the associated table.
  446. *
  447. * This function will add entries in the `contain` graph.
  448. *
  449. * ### Example:
  450. *
  451. * ```
  452. * // Bring only articles that were tagged with 'cake'
  453. * $query->matching('Tags', function ($q) {
  454. * return $q->where(['name' => 'cake']);
  455. * );
  456. * ```
  457. *
  458. * It is possible to filter by deep associations by using dot notation:
  459. *
  460. * ### Example:
  461. *
  462. * ```
  463. * // Bring only articles that were commented by 'markstory'
  464. * $query->matching('Comments.Users', function ($q) {
  465. * return $q->where(['username' => 'markstory']);
  466. * );
  467. * ```
  468. *
  469. * As this function will create `INNER JOIN`, you might want to consider
  470. * calling `distinct` on this query as you might get duplicate rows if
  471. * your conditions don't filter them already. This might be the case, for example,
  472. * of the same user commenting more than once in the same article.
  473. *
  474. * ### Example:
  475. *
  476. * ```
  477. * // Bring unique articles that were commented by 'markstory'
  478. * $query->distinct(['Articles.id'])
  479. * ->matching('Comments.Users', function ($q) {
  480. * return $q->where(['username' => 'markstory']);
  481. * );
  482. * ```
  483. *
  484. * Please note that the query passed to the closure will only accept calling
  485. * `select`, `where`, `andWhere` and `orWhere` on it. If you wish to
  486. * add more complex clauses you can do it directly in the main query.
  487. *
  488. * @param string $assoc The association to filter by
  489. * @param callable|null $builder a function that will receive a pre-made query object
  490. * that can be used to add custom conditions or selecting some fields
  491. * @return $this
  492. */
  493. public function matching($assoc, callable $builder = null)
  494. {
  495. $result = $this->getEagerLoader()->setMatching($assoc, $builder)->getMatching();
  496. $this->_addAssociationsToTypeMap($this->repository(), $this->getTypeMap(), $result);
  497. $this->_dirty();
  498. return $this;
  499. }
  500. /**
  501. * Creates a LEFT JOIN with the passed association table while preserving
  502. * the foreign key matching and the custom conditions that were originally set
  503. * for it.
  504. *
  505. * This function will add entries in the `contain` graph.
  506. *
  507. * ### Example:
  508. *
  509. * ```
  510. * // Get the count of articles per user
  511. * $usersQuery
  512. * ->select(['total_articles' => $query->func()->count('Articles.id')])
  513. * ->leftJoinWith('Articles')
  514. * ->group(['Users.id'])
  515. * ->enableAutoFields(true);
  516. * ```
  517. *
  518. * You can also customize the conditions passed to the LEFT JOIN:
  519. *
  520. * ```
  521. * // Get the count of articles per user with at least 5 votes
  522. * $usersQuery
  523. * ->select(['total_articles' => $query->func()->count('Articles.id')])
  524. * ->leftJoinWith('Articles', function ($q) {
  525. * return $q->where(['Articles.votes >=' => 5]);
  526. * })
  527. * ->group(['Users.id'])
  528. * ->enableAutoFields(true);
  529. * ```
  530. *
  531. * This will create the following SQL:
  532. *
  533. * ```
  534. * SELECT COUNT(Articles.id) AS total_articles, Users.*
  535. * FROM users Users
  536. * LEFT JOIN articles Articles ON Articles.user_id = Users.id AND Articles.votes >= 5
  537. * GROUP BY USers.id
  538. * ```
  539. *
  540. * It is possible to left join deep associations by using dot notation
  541. *
  542. * ### Example:
  543. *
  544. * ```
  545. * // Total comments in articles by 'markstory'
  546. * $query
  547. * ->select(['total_comments' => $query->func()->count('Comments.id')])
  548. * ->leftJoinWith('Comments.Users', function ($q) {
  549. * return $q->where(['username' => 'markstory']);
  550. * )
  551. * ->group(['Users.id']);
  552. * ```
  553. *
  554. * Please note that the query passed to the closure will only accept calling
  555. * `select`, `where`, `andWhere` and `orWhere` on it. If you wish to
  556. * add more complex clauses you can do it directly in the main query.
  557. *
  558. * @param string $assoc The association to join with
  559. * @param callable|null $builder a function that will receive a pre-made query object
  560. * that can be used to add custom conditions or selecting some fields
  561. * @return $this
  562. */
  563. public function leftJoinWith($assoc, callable $builder = null)
  564. {
  565. $result = $this->getEagerLoader()
  566. ->setMatching($assoc, $builder, [
  567. 'joinType' => QueryInterface::JOIN_TYPE_LEFT,
  568. 'fields' => false
  569. ])
  570. ->getMatching();
  571. $this->_addAssociationsToTypeMap($this->repository(), $this->getTypeMap(), $result);
  572. $this->_dirty();
  573. return $this;
  574. }
  575. /**
  576. * Creates an INNER JOIN with the passed association table while preserving
  577. * the foreign key matching and the custom conditions that were originally set
  578. * for it.
  579. *
  580. * This function will add entries in the `contain` graph.
  581. *
  582. * ### Example:
  583. *
  584. * ```
  585. * // Bring only articles that were tagged with 'cake'
  586. * $query->innerJoinWith('Tags', function ($q) {
  587. * return $q->where(['name' => 'cake']);
  588. * );
  589. * ```
  590. *
  591. * This will create the following SQL:
  592. *
  593. * ```
  594. * SELECT Articles.*
  595. * FROM articles Articles
  596. * INNER JOIN tags Tags ON Tags.name = 'cake'
  597. * INNER JOIN articles_tags ArticlesTags ON ArticlesTags.tag_id = Tags.id
  598. * AND ArticlesTags.articles_id = Articles.id
  599. * ```
  600. *
  601. * This function works the same as `matching()` with the difference that it
  602. * will select no fields from the association.
  603. *
  604. * @param string $assoc The association to join with
  605. * @param callable|null $builder a function that will receive a pre-made query object
  606. * that can be used to add custom conditions or selecting some fields
  607. * @return $this
  608. * @see \Cake\ORM\Query::matching()
  609. */
  610. public function innerJoinWith($assoc, callable $builder = null)
  611. {
  612. $result = $this->getEagerLoader()
  613. ->setMatching($assoc, $builder, [
  614. 'joinType' => QueryInterface::JOIN_TYPE_INNER,
  615. 'fields' => false
  616. ])
  617. ->getMatching();
  618. $this->_addAssociationsToTypeMap($this->repository(), $this->getTypeMap(), $result);
  619. $this->_dirty();
  620. return $this;
  621. }
  622. /**
  623. * Adds filtering conditions to this query to only bring rows that have no match
  624. * to another from an associated table, based on conditions in the associated table.
  625. *
  626. * This function will add entries in the `contain` graph.
  627. *
  628. * ### Example:
  629. *
  630. * ```
  631. * // Bring only articles that were not tagged with 'cake'
  632. * $query->notMatching('Tags', function ($q) {
  633. * return $q->where(['name' => 'cake']);
  634. * );
  635. * ```
  636. *
  637. * It is possible to filter by deep associations by using dot notation:
  638. *
  639. * ### Example:
  640. *
  641. * ```
  642. * // Bring only articles that weren't commented by 'markstory'
  643. * $query->notMatching('Comments.Users', function ($q) {
  644. * return $q->where(['username' => 'markstory']);
  645. * );
  646. * ```
  647. *
  648. * As this function will create a `LEFT JOIN`, you might want to consider
  649. * calling `distinct` on this query as you might get duplicate rows if
  650. * your conditions don't filter them already. This might be the case, for example,
  651. * of the same article having multiple comments.
  652. *
  653. * ### Example:
  654. *
  655. * ```
  656. * // Bring unique articles that were commented by 'markstory'
  657. * $query->distinct(['Articles.id'])
  658. * ->notMatching('Comments.Users', function ($q) {
  659. * return $q->where(['username' => 'markstory']);
  660. * );
  661. * ```
  662. *
  663. * Please note that the query passed to the closure will only accept calling
  664. * `select`, `where`, `andWhere` and `orWhere` on it. If you wish to
  665. * add more complex clauses you can do it directly in the main query.
  666. *
  667. * @param string $assoc The association to filter by
  668. * @param callable|null $builder a function that will receive a pre-made query object
  669. * that can be used to add custom conditions or selecting some fields
  670. * @return $this
  671. */
  672. public function notMatching($assoc, callable $builder = null)
  673. {
  674. $result = $this->getEagerLoader()
  675. ->setMatching($assoc, $builder, [
  676. 'joinType' => QueryInterface::JOIN_TYPE_LEFT,
  677. 'fields' => false,
  678. 'negateMatch' => true
  679. ])
  680. ->getMatching();
  681. $this->_addAssociationsToTypeMap($this->repository(), $this->getTypeMap(), $result);
  682. $this->_dirty();
  683. return $this;
  684. }
  685. /**
  686. * {@inheritDoc}
  687. *
  688. * Populates or adds parts to current query clauses using an array.
  689. * This is handy for passing all query clauses at once. The option array accepts:
  690. *
  691. * - fields: Maps to the select method
  692. * - conditions: Maps to the where method
  693. * - limit: Maps to the limit method
  694. * - order: Maps to the order method
  695. * - offset: Maps to the offset method
  696. * - group: Maps to the group method
  697. * - having: Maps to the having method
  698. * - contain: Maps to the contain options for eager loading
  699. * - join: Maps to the join method
  700. * - page: Maps to the page method
  701. *
  702. * ### Example:
  703. *
  704. * ```
  705. * $query->applyOptions([
  706. * 'fields' => ['id', 'name'],
  707. * 'conditions' => [
  708. * 'created >=' => '2013-01-01'
  709. * ],
  710. * 'limit' => 10
  711. * ]);
  712. * ```
  713. *
  714. * Is equivalent to:
  715. *
  716. * ```
  717. * $query
  718. * ->select(['id', 'name'])
  719. * ->where(['created >=' => '2013-01-01'])
  720. * ->limit(10)
  721. * ```
  722. */
  723. public function applyOptions(array $options)
  724. {
  725. $valid = [
  726. 'fields' => 'select',
  727. 'conditions' => 'where',
  728. 'join' => 'join',
  729. 'order' => 'order',
  730. 'limit' => 'limit',
  731. 'offset' => 'offset',
  732. 'group' => 'group',
  733. 'having' => 'having',
  734. 'contain' => 'contain',
  735. 'page' => 'page',
  736. ];
  737. ksort($options);
  738. foreach ($options as $option => $values) {
  739. if (isset($valid[$option], $values)) {
  740. $this->{$valid[$option]}($values);
  741. } else {
  742. $this->_options[$option] = $values;
  743. }
  744. }
  745. return $this;
  746. }
  747. /**
  748. * Creates a copy of this current query, triggers beforeFind and resets some state.
  749. *
  750. * The following state will be cleared:
  751. *
  752. * - autoFields
  753. * - limit
  754. * - offset
  755. * - map/reduce functions
  756. * - result formatters
  757. * - order
  758. * - containments
  759. *
  760. * This method creates query clones that are useful when working with subqueries.
  761. *
  762. * @return \Cake\ORM\Query
  763. */
  764. public function cleanCopy()
  765. {
  766. $clone = clone $this;
  767. $clone->setEagerLoader(clone $this->getEagerLoader());
  768. $clone->triggerBeforeFind();
  769. $clone->enableAutoFields(false);
  770. $clone->limit(null);
  771. $clone->order([], true);
  772. $clone->offset(null);
  773. $clone->mapReduce(null, null, true);
  774. $clone->formatResults(null, true);
  775. $clone->setSelectTypeMap(new TypeMap());
  776. $clone->decorateResults(null, true);
  777. return $clone;
  778. }
  779. /**
  780. * Object clone hook.
  781. *
  782. * Destroys the clones inner iterator and clones the value binder, and eagerloader instances.
  783. *
  784. * @return void
  785. */
  786. public function __clone()
  787. {
  788. parent::__clone();
  789. if ($this->_eagerLoader) {
  790. $this->_eagerLoader = clone $this->_eagerLoader;
  791. }
  792. }
  793. /**
  794. * {@inheritDoc}
  795. *
  796. * Returns the COUNT(*) for the query. If the query has not been
  797. * modified, and the count has already been performed the cached
  798. * value is returned
  799. */
  800. public function count()
  801. {
  802. if ($this->_resultsCount === null) {
  803. $this->_resultsCount = $this->_performCount();
  804. }
  805. return $this->_resultsCount;
  806. }
  807. /**
  808. * Performs and returns the COUNT(*) for the query.
  809. *
  810. * @return int
  811. */
  812. protected function _performCount()
  813. {
  814. $query = $this->cleanCopy();
  815. $counter = $this->_counter;
  816. if ($counter) {
  817. $query->counter(null);
  818. return (int)$counter($query);
  819. }
  820. $complex = (
  821. $query->clause('distinct') ||
  822. count($query->clause('group')) ||
  823. count($query->clause('union')) ||
  824. $query->clause('having')
  825. );
  826. if (!$complex) {
  827. // Expression fields could have bound parameters.
  828. foreach ($query->clause('select') as $field) {
  829. if ($field instanceof ExpressionInterface) {
  830. $complex = true;
  831. break;
  832. }
  833. }
  834. }
  835. if (!$complex && $this->_valueBinder !== null) {
  836. $order = $this->clause('order');
  837. $complex = $order === null ? false : $order->hasNestedExpression();
  838. }
  839. $count = ['count' => $query->func()->count('*')];
  840. if (!$complex) {
  841. $query->getEagerLoader()->enableAutoFields(false);
  842. $statement = $query
  843. ->select($count, true)
  844. ->enableAutoFields(false)
  845. ->execute();
  846. } else {
  847. $statement = $this->getConnection()->newQuery()
  848. ->select($count)
  849. ->from(['count_source' => $query])
  850. ->execute();
  851. }
  852. $result = $statement->fetch('assoc')['count'];
  853. $statement->closeCursor();
  854. return (int)$result;
  855. }
  856. /**
  857. * Registers a callable function that will be executed when the `count` method in
  858. * this query is called. The return value for the function will be set as the
  859. * return value of the `count` method.
  860. *
  861. * This is particularly useful when you need to optimize a query for returning the
  862. * count, for example removing unnecessary joins, removing group by or just return
  863. * an estimated number of rows.
  864. *
  865. * The callback will receive as first argument a clone of this query and not this
  866. * query itself.
  867. *
  868. * If the first param is a null value, the built-in counter function will be called
  869. * instead
  870. *
  871. * @param callable|null $counter The counter value
  872. * @return $this
  873. */
  874. public function counter($counter)
  875. {
  876. $this->_counter = $counter;
  877. return $this;
  878. }
  879. /**
  880. * Toggle hydrating entities.
  881. *
  882. * If set to false array results will be returned for the query.
  883. *
  884. * @param bool $enable Use a boolean to set the hydration mode.
  885. * @return $this
  886. */
  887. public function enableHydration($enable = true)
  888. {
  889. $this->_dirty();
  890. $this->_hydrate = (bool)$enable;
  891. return $this;
  892. }
  893. /**
  894. * Returns the current hydration mode.
  895. *
  896. * @return bool
  897. */
  898. public function isHydrationEnabled()
  899. {
  900. return $this->_hydrate;
  901. }
  902. /**
  903. * Toggle hydrating entities.
  904. *
  905. * If set to false array results will be returned.
  906. *
  907. * @deprecated 3.4.0 Use enableHydration()/isHydrationEnabled() instead.
  908. * @param bool|null $enable Use a boolean to set the hydration mode.
  909. * Null will fetch the current hydration mode.
  910. * @return bool|$this A boolean when reading, and $this when setting the mode.
  911. */
  912. public function hydrate($enable = null)
  913. {
  914. deprecationWarning(
  915. 'Query::hydrate() is deprecated. ' .
  916. 'Use enableHydration()/isHydrationEnabled() instead.'
  917. );
  918. if ($enable === null) {
  919. return $this->isHydrationEnabled();
  920. }
  921. return $this->enableHydration($enable);
  922. }
  923. /**
  924. * {@inheritDoc}
  925. *
  926. * @return $this
  927. * @throws \RuntimeException When you attempt to cache a non-select query.
  928. */
  929. public function cache($key, $config = 'default')
  930. {
  931. if ($this->_type !== 'select' && $this->_type !== null) {
  932. throw new RuntimeException('You cannot cache the results of non-select queries.');
  933. }
  934. return $this->_cache($key, $config);
  935. }
  936. /**
  937. * {@inheritDoc}
  938. *
  939. * @throws \RuntimeException if this method is called on a non-select Query.
  940. */
  941. public function all()
  942. {
  943. if ($this->_type !== 'select' && $this->_type !== null) {
  944. throw new RuntimeException(
  945. 'You cannot call all() on a non-select query. Use execute() instead.'
  946. );
  947. }
  948. return $this->_all();
  949. }
  950. /**
  951. * Trigger the beforeFind event on the query's repository object.
  952. *
  953. * Will not trigger more than once, and only for select queries.
  954. *
  955. * @return void
  956. */
  957. public function triggerBeforeFind()
  958. {
  959. if (!$this->_beforeFindFired && $this->_type === 'select') {
  960. $table = $this->repository();
  961. $this->_beforeFindFired = true;
  962. /* @var \Cake\Event\EventDispatcherInterface $table */
  963. $table->dispatchEvent('Model.beforeFind', [
  964. $this,
  965. new ArrayObject($this->_options),
  966. !$this->isEagerLoaded()
  967. ]);
  968. }
  969. }
  970. /**
  971. * {@inheritDoc}
  972. */
  973. public function sql(ValueBinder $binder = null)
  974. {
  975. $this->triggerBeforeFind();
  976. $this->_transformQuery();
  977. return parent::sql($binder);
  978. }
  979. /**
  980. * Executes this query and returns a ResultSet object containing the results.
  981. * This will also setup the correct statement class in order to eager load deep
  982. * associations.
  983. *
  984. * @return \Cake\ORM\ResultSet
  985. */
  986. protected function _execute()
  987. {
  988. $this->triggerBeforeFind();
  989. if ($this->_results) {
  990. $decorator = $this->_decoratorClass();
  991. return new $decorator($this->_results);
  992. }
  993. $statement = $this->getEagerLoader()->loadExternal($this, $this->execute());
  994. return new ResultSet($this, $statement);
  995. }
  996. /**
  997. * Applies some defaults to the query object before it is executed.
  998. *
  999. * Specifically add the FROM clause, adds default table fields if none are
  1000. * specified and applies the joins required to eager load associations defined
  1001. * using `contain`
  1002. *
  1003. * It also sets the default types for the columns in the select clause
  1004. *
  1005. * @see \Cake\Database\Query::execute()
  1006. * @return void
  1007. */
  1008. protected function _transformQuery()
  1009. {
  1010. if (!$this->_dirty || $this->_type !== 'select') {
  1011. return;
  1012. }
  1013. if (empty($this->_parts['from'])) {
  1014. $this->from([$this->_repository->getAlias() => $this->_repository->getTable()]);
  1015. }
  1016. $this->_addDefaultFields();
  1017. $this->getEagerLoader()->attachAssociations($this, $this->_repository, !$this->_hasFields);
  1018. $this->_addDefaultSelectTypes();
  1019. }
  1020. /**
  1021. * Inspects if there are any set fields for selecting, otherwise adds all
  1022. * the fields for the default table.
  1023. *
  1024. * @return void
  1025. */
  1026. protected function _addDefaultFields()
  1027. {
  1028. $select = $this->clause('select');
  1029. $this->_hasFields = true;
  1030. if (!count($select) || $this->_autoFields === true) {
  1031. $this->_hasFields = false;
  1032. $this->select($this->repository()->getSchema()->columns());
  1033. $select = $this->clause('select');
  1034. }
  1035. $aliased = $this->aliasFields($select, $this->repository()->getAlias());
  1036. $this->select($aliased, true);
  1037. }
  1038. /**
  1039. * Sets the default types for converting the fields in the select clause
  1040. *
  1041. * @return void
  1042. */
  1043. protected function _addDefaultSelectTypes()
  1044. {
  1045. $typeMap = $this->getTypeMap()->getDefaults();
  1046. $select = $this->clause('select');
  1047. $types = [];
  1048. foreach ($select as $alias => $value) {
  1049. if (isset($typeMap[$alias])) {
  1050. $types[$alias] = $typeMap[$alias];
  1051. continue;
  1052. }
  1053. if (is_string($value) && isset($typeMap[$value])) {
  1054. $types[$alias] = $typeMap[$value];
  1055. }
  1056. if ($value instanceof TypedResultInterface) {
  1057. $types[$alias] = $value->getReturnType();
  1058. }
  1059. }
  1060. $this->getSelectTypeMap()->addDefaults($types);
  1061. }
  1062. /**
  1063. * {@inheritDoc}
  1064. *
  1065. * @see \Cake\ORM\Table::find()
  1066. */
  1067. public function find($finder, array $options = [])
  1068. {
  1069. return $this->repository()->callFinder($finder, $this, $options);
  1070. }
  1071. /**
  1072. * Marks a query as dirty, removing any preprocessed information
  1073. * from in memory caching such as previous results
  1074. *
  1075. * @return void
  1076. */
  1077. protected function _dirty()
  1078. {
  1079. $this->_results = null;
  1080. $this->_resultsCount = null;
  1081. parent::_dirty();
  1082. }
  1083. /**
  1084. * Create an update query.
  1085. *
  1086. * This changes the query type to be 'update'.
  1087. * Can be combined with set() and where() methods to create update queries.
  1088. *
  1089. * @param string|null $table Unused parameter.
  1090. * @return $this
  1091. */
  1092. public function update($table = null)
  1093. {
  1094. $table = $table ?: $this->repository()->getTable();
  1095. return parent::update($table);
  1096. }
  1097. /**
  1098. * Create a delete query.
  1099. *
  1100. * This changes the query type to be 'delete'.
  1101. * Can be combined with the where() method to create delete queries.
  1102. *
  1103. * @param string|null $table Unused parameter.
  1104. * @return $this
  1105. */
  1106. public function delete($table = null)
  1107. {
  1108. $repo = $this->repository();
  1109. $this->from([$repo->getAlias() => $repo->getTable()]);
  1110. return parent::delete();
  1111. }
  1112. /**
  1113. * Create an insert query.
  1114. *
  1115. * This changes the query type to be 'insert'.
  1116. * Note calling this method will reset any data previously set
  1117. * with Query::values()
  1118. *
  1119. * Can be combined with the where() method to create delete queries.
  1120. *
  1121. * @param array $columns The columns to insert into.
  1122. * @param array $types A map between columns & their datatypes.
  1123. * @return $this
  1124. */
  1125. public function insert(array $columns, array $types = [])
  1126. {
  1127. $table = $this->repository()->getTable();
  1128. $this->into($table);
  1129. return parent::insert($columns, $types);
  1130. }
  1131. /**
  1132. * {@inheritDoc}
  1133. *
  1134. * @throws \BadMethodCallException if the method is called for a non-select query
  1135. */
  1136. public function __call($method, $arguments)
  1137. {
  1138. if ($this->type() === 'select') {
  1139. return $this->_call($method, $arguments);
  1140. }
  1141. throw new \BadMethodCallException(
  1142. sprintf('Cannot call method "%s" on a "%s" query', $method, $this->type())
  1143. );
  1144. }
  1145. /**
  1146. * {@inheritDoc}
  1147. */
  1148. public function __debugInfo()
  1149. {
  1150. $eagerLoader = $this->getEagerLoader();
  1151. return parent::__debugInfo() + [
  1152. 'hydrate' => $this->_hydrate,
  1153. 'buffered' => $this->_useBufferedResults,
  1154. 'formatters' => count($this->_formatters),
  1155. 'mapReducers' => count($this->_mapReduce),
  1156. 'contain' => $eagerLoader ? $eagerLoader->contain() : [],
  1157. 'matching' => $eagerLoader ? $eagerLoader->getMatching() : [],
  1158. 'extraOptions' => $this->_options,
  1159. 'repository' => $this->_repository
  1160. ];
  1161. }
  1162. /**
  1163. * Executes the query and converts the result set into JSON.
  1164. *
  1165. * Part of JsonSerializable interface.
  1166. *
  1167. * @return \Cake\Datasource\ResultSetInterface The data to convert to JSON.
  1168. */
  1169. public function jsonSerialize()
  1170. {
  1171. return $this->all();
  1172. }
  1173. /**
  1174. * Sets whether or not the ORM should automatically append fields.
  1175. *
  1176. * By default calling select() will disable auto-fields. You can re-enable
  1177. * auto-fields with this method.
  1178. *
  1179. * @param bool $value Set true to enable, false to disable.
  1180. * @return $this
  1181. */
  1182. public function enableAutoFields($value = true)
  1183. {
  1184. $this->_autoFields = (bool)$value;
  1185. return $this;
  1186. }
  1187. /**
  1188. * Gets whether or not the ORM should automatically append fields.
  1189. *
  1190. * By default calling select() will disable auto-fields. You can re-enable
  1191. * auto-fields with enableAutoFields().
  1192. *
  1193. * @return bool The current value.
  1194. */
  1195. public function isAutoFieldsEnabled()
  1196. {
  1197. return $this->_autoFields;
  1198. }
  1199. /**
  1200. * Get/Set whether or not the ORM should automatically append fields.
  1201. *
  1202. * By default calling select() will disable auto-fields. You can re-enable
  1203. * auto-fields with this method.
  1204. *
  1205. * @deprecated 3.4.0 Use enableAutoFields()/isAutoFieldsEnabled() instead.
  1206. * @param bool|null $value The value to set or null to read the current value.
  1207. * @return bool|$this Either the current value or the query object.
  1208. */
  1209. public function autoFields($value = null)
  1210. {
  1211. deprecationWarning(
  1212. 'Query::autoFields() is deprecated. ' .
  1213. 'Use enableAutoFields()/isAutoFieldsEnabled() instead.'
  1214. );
  1215. if ($value === null) {
  1216. return $this->isAutoFieldsEnabled();
  1217. }
  1218. return $this->enableAutoFields($value);
  1219. }
  1220. /**
  1221. * Decorates the results iterator with MapReduce routines and formatters
  1222. *
  1223. * @param \Traversable $result Original results
  1224. * @return \Cake\Datasource\ResultSetInterface
  1225. */
  1226. protected function _decorateResults($result)
  1227. {
  1228. $result = $this->_applyDecorators($result);
  1229. if (!($result instanceof ResultSet) && $this->isBufferedResultsEnabled()) {
  1230. $class = $this->_decoratorClass();
  1231. $result = new $class($result->buffered());
  1232. }
  1233. return $result;
  1234. }
  1235. }