Query.php 45 KB

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