QueryTest.php 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://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. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since 3.0.0
  13. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Test\TestCase\ORM;
  16. use Cake\Database\Expression\IdentifierExpression;
  17. use Cake\Database\Expression\OrderByExpression;
  18. use Cake\Database\Expression\QueryExpression;
  19. use Cake\Database\TypeMap;
  20. use Cake\Datasource\ConnectionManager;
  21. use Cake\ORM\Query;
  22. use Cake\ORM\ResultSet;
  23. use Cake\ORM\Table;
  24. use Cake\ORM\TableRegistry;
  25. use Cake\TestSuite\TestCase;
  26. /**
  27. * Tests Query class
  28. */
  29. class QueryTest extends TestCase {
  30. /**
  31. * Fixture to be used
  32. *
  33. * @var array
  34. */
  35. public $fixtures = ['core.articles', 'core.authors', 'core.tags',
  36. 'core.articles_tags', 'core.posts'];
  37. /**
  38. * setUp method
  39. *
  40. * @return void
  41. */
  42. public function setUp() {
  43. parent::setUp();
  44. $this->connection = ConnectionManager::get('test');
  45. $schema = [
  46. 'id' => ['type' => 'integer'],
  47. '_constraints' => [
  48. 'primary' => ['type' => 'primary', 'columns' => ['id']]
  49. ]
  50. ];
  51. $schema1 = [
  52. 'id' => ['type' => 'integer'],
  53. 'name' => ['type' => 'string'],
  54. 'phone' => ['type' => 'string'],
  55. '_constraints' => [
  56. 'primary' => ['type' => 'primary', 'columns' => ['id']]
  57. ]
  58. ];
  59. $schema2 = [
  60. 'id' => ['type' => 'integer'],
  61. 'total' => ['type' => 'string'],
  62. 'placed' => ['type' => 'datetime'],
  63. '_constraints' => [
  64. 'primary' => ['type' => 'primary', 'columns' => ['id']]
  65. ]
  66. ];
  67. $this->table = $table = TableRegistry::get('foo', ['schema' => $schema]);
  68. $clients = TableRegistry::get('clients', ['schema' => $schema1]);
  69. $orders = TableRegistry::get('orders', ['schema' => $schema2]);
  70. $companies = TableRegistry::get('companies', ['schema' => $schema, 'table' => 'organizations']);
  71. $orderTypes = TableRegistry::get('orderTypes', ['schema' => $schema]);
  72. $stuff = TableRegistry::get('stuff', ['schema' => $schema, 'table' => 'things']);
  73. $stuffTypes = TableRegistry::get('stuffTypes', ['schema' => $schema]);
  74. $categories = TableRegistry::get('categories', ['schema' => $schema]);
  75. $table->belongsTo('clients');
  76. $clients->hasOne('orders');
  77. $clients->belongsTo('companies');
  78. $orders->belongsTo('orderTypes');
  79. $orders->hasOne('stuff');
  80. $stuff->belongsTo('stuffTypes');
  81. $companies->belongsTo('categories');
  82. $this->fooTypeMap = new TypeMap(['foo.id' => 'integer', 'id' => 'integer']);
  83. }
  84. /**
  85. * tearDown method
  86. *
  87. * @return void
  88. */
  89. public function tearDown() {
  90. parent::tearDown();
  91. TableRegistry::clear();
  92. }
  93. /**
  94. * Provides strategies for associations that can be joined
  95. *
  96. * @return void
  97. */
  98. public function internalStategiesProvider() {
  99. return [['join'], ['select'], ['subquery']];
  100. }
  101. /**
  102. * Tests that results are grouped correctly when using contain()
  103. * and results are not hydrated
  104. *
  105. * @dataProvider internalStategiesProvider
  106. * @return void
  107. */
  108. public function testContainResultFetchingOneLevel($strategy) {
  109. $table = TableRegistry::get('articles', ['table' => 'articles']);
  110. $table->belongsTo('authors', ['strategy' => $strategy]);
  111. $query = new Query($this->connection, $table);
  112. $results = $query->select()
  113. ->contain('authors')
  114. ->hydrate(false)
  115. ->order(['articles.id' => 'asc'])
  116. ->toArray();
  117. $expected = [
  118. [
  119. 'id' => 1,
  120. 'title' => 'First Article',
  121. 'body' => 'First Article Body',
  122. 'author_id' => 1,
  123. 'published' => 'Y',
  124. 'author' => [
  125. 'id' => 1,
  126. 'name' => 'mariano'
  127. ]
  128. ],
  129. [
  130. 'id' => 2,
  131. 'title' => 'Second Article',
  132. 'body' => 'Second Article Body',
  133. 'author_id' => 3,
  134. 'published' => 'Y',
  135. 'author' => [
  136. 'id' => 3,
  137. 'name' => 'larry'
  138. ]
  139. ],
  140. [
  141. 'id' => 3,
  142. 'title' => 'Third Article',
  143. 'body' => 'Third Article Body',
  144. 'author_id' => 1,
  145. 'published' => 'Y',
  146. 'author' => [
  147. 'id' => 1,
  148. 'name' => 'mariano'
  149. ]
  150. ],
  151. ];
  152. $this->assertEquals($expected, $results);
  153. }
  154. /**
  155. * Data provider for the two types of strategies HasMany implements
  156. *
  157. * @return void
  158. */
  159. public function strategiesProvider() {
  160. return [['subquery'], ['select']];
  161. }
  162. /**
  163. * Tests that HasMany associations are correctly eager loaded and results
  164. * correctly nested when no hydration is used
  165. * Also that the query object passes the correct parent model keys to the
  166. * association objects in order to perform eager loading with select strategy
  167. *
  168. * @dataProvider strategiesProvider
  169. * @return void
  170. */
  171. public function testHasManyEagerLoadingNoHydration($strategy) {
  172. $table = TableRegistry::get('authors');
  173. TableRegistry::get('articles');
  174. $table->hasMany('articles', [
  175. 'propertyName' => 'articles',
  176. 'strategy' => $strategy,
  177. 'sort' => ['articles.id' => 'asc']
  178. ]);
  179. $query = new Query($this->connection, $table);
  180. $results = $query->select()
  181. ->contain('articles')
  182. ->hydrate(false)
  183. ->toArray();
  184. $expected = [
  185. [
  186. 'id' => 1,
  187. 'name' => 'mariano',
  188. 'articles' => [
  189. [
  190. 'id' => 1,
  191. 'title' => 'First Article',
  192. 'body' => 'First Article Body',
  193. 'author_id' => 1,
  194. 'published' => 'Y',
  195. ],
  196. [
  197. 'id' => 3,
  198. 'title' => 'Third Article',
  199. 'body' => 'Third Article Body',
  200. 'author_id' => 1,
  201. 'published' => 'Y',
  202. ],
  203. ]
  204. ],
  205. [
  206. 'id' => 2,
  207. 'name' => 'nate',
  208. 'articles' => [],
  209. ],
  210. [
  211. 'id' => 3,
  212. 'name' => 'larry',
  213. 'articles' => [
  214. [
  215. 'id' => 2,
  216. 'title' => 'Second Article',
  217. 'body' => 'Second Article Body',
  218. 'author_id' => 3,
  219. 'published' => 'Y'
  220. ]
  221. ]
  222. ],
  223. [
  224. 'id' => 4,
  225. 'name' => 'garrett',
  226. 'articles' => [],
  227. ]
  228. ];
  229. $this->assertEquals($expected, $results);
  230. $results = $query->repository($table)
  231. ->select()
  232. ->contain(['articles' => ['conditions' => ['articles.id' => 2]]])
  233. ->hydrate(false)
  234. ->toArray();
  235. $expected[0]['articles'] = [];
  236. $this->assertEquals($expected, $results);
  237. $this->assertEquals($table->association('articles')->strategy(), $strategy);
  238. }
  239. /**
  240. * Tests that it is possible to count results containing hasMany associations
  241. * both hydrating and not hydrating the results.
  242. *
  243. * @dataProvider strategiesProvider
  244. * @return void
  245. */
  246. public function testHasManyEagerLoadingCount($strategy) {
  247. $table = TableRegistry::get('authors');
  248. TableRegistry::get('articles');
  249. $table->hasMany('articles', [
  250. 'property' => 'articles',
  251. 'strategy' => $strategy,
  252. 'sort' => ['articles.id' => 'asc']
  253. ]);
  254. $query = new Query($this->connection, $table);
  255. $query = $query->select()
  256. ->contain('articles');
  257. $expected = 4;
  258. $results = $query->hydrate(false)
  259. ->count();
  260. $this->assertEquals($expected, $results);
  261. $results = $query->hydrate(true)
  262. ->count();
  263. $this->assertEquals($expected, $results);
  264. }
  265. /**
  266. * Tests that it is possible to set fields & order in a hasMany result set
  267. *
  268. * @dataProvider strategiesProvider
  269. * @return void
  270. */
  271. public function testHasManyEagerLoadingFieldsAndOrderNoHydration($strategy) {
  272. $table = TableRegistry::get('authors');
  273. TableRegistry::get('articles');
  274. $table->hasMany('articles', ['propertyName' => 'articles'] + compact('strategy'));
  275. $query = new Query($this->connection, $table);
  276. $results = $query->select()
  277. ->contain([
  278. 'articles' => [
  279. 'fields' => ['title', 'author_id'],
  280. 'sort' => ['articles.id' => 'DESC']
  281. ]
  282. ])
  283. ->hydrate(false)
  284. ->toArray();
  285. $expected = [
  286. [
  287. 'id' => 1,
  288. 'name' => 'mariano',
  289. 'articles' => [
  290. ['title' => 'Third Article', 'author_id' => 1],
  291. ['title' => 'First Article', 'author_id' => 1],
  292. ]
  293. ],
  294. [
  295. 'id' => 2,
  296. 'name' => 'nate',
  297. 'articles' => [],
  298. ],
  299. [
  300. 'id' => 3,
  301. 'name' => 'larry',
  302. 'articles' => [
  303. ['title' => 'Second Article', 'author_id' => 3],
  304. ]
  305. ],
  306. [
  307. 'id' => 4,
  308. 'name' => 'garrett',
  309. 'articles' => [],
  310. ],
  311. ];
  312. $this->assertEquals($expected, $results);
  313. }
  314. /**
  315. * Tests that deep associations can be eagerly loaded
  316. *
  317. * @dataProvider strategiesProvider
  318. * @return void
  319. */
  320. public function testHasManyEagerLoadingDeep($strategy) {
  321. $table = TableRegistry::get('authors');
  322. $article = TableRegistry::get('articles');
  323. $table->hasMany('articles', [
  324. 'propertyName' => 'articles',
  325. 'strategy' => $strategy,
  326. 'sort' => ['articles.id' => 'asc']
  327. ]);
  328. $article->belongsTo('authors');
  329. $query = new Query($this->connection, $table);
  330. $results = $query->select()
  331. ->contain(['articles' => ['authors']])
  332. ->hydrate(false)
  333. ->toArray();
  334. $expected = [
  335. [
  336. 'id' => 1,
  337. 'name' => 'mariano',
  338. 'articles' => [
  339. [
  340. 'id' => 1,
  341. 'title' => 'First Article',
  342. 'author_id' => 1,
  343. 'body' => 'First Article Body',
  344. 'published' => 'Y',
  345. 'author' => ['id' => 1, 'name' => 'mariano']
  346. ],
  347. [
  348. 'id' => 3,
  349. 'title' => 'Third Article',
  350. 'author_id' => 1,
  351. 'body' => 'Third Article Body',
  352. 'published' => 'Y',
  353. 'author' => ['id' => 1, 'name' => 'mariano']
  354. ],
  355. ]
  356. ],
  357. [
  358. 'id' => 2,
  359. 'name' => 'nate',
  360. 'articles' => [],
  361. ],
  362. [
  363. 'id' => 3,
  364. 'name' => 'larry',
  365. 'articles' => [
  366. [
  367. 'id' => 2,
  368. 'title' => 'Second Article',
  369. 'author_id' => 3,
  370. 'body' => 'Second Article Body',
  371. 'published' => 'Y',
  372. 'author' => ['id' => 3, 'name' => 'larry']
  373. ],
  374. ]
  375. ],
  376. [
  377. 'id' => 4,
  378. 'name' => 'garrett',
  379. 'articles' => [],
  380. ]
  381. ];
  382. $this->assertEquals($expected, $results);
  383. }
  384. /**
  385. * Tests that hasMany associations can be loaded even when related to a secondary
  386. * model in the query
  387. *
  388. * @dataProvider strategiesProvider
  389. * @return void
  390. */
  391. public function testHasManyEagerLoadingFromSecondaryTable($strategy) {
  392. $author = TableRegistry::get('authors');
  393. $article = TableRegistry::get('articles');
  394. $post = TableRegistry::get('posts');
  395. $author->hasMany('posts', compact('strategy'));
  396. $article->belongsTo('authors');
  397. $query = new Query($this->connection, $article);
  398. $results = $query->select()
  399. ->contain(['authors' => ['posts']])
  400. ->order(['articles.id' => 'ASC'])
  401. ->hydrate(false)
  402. ->toArray();
  403. $expected = [
  404. [
  405. 'id' => 1,
  406. 'title' => 'First Article',
  407. 'body' => 'First Article Body',
  408. 'author_id' => 1,
  409. 'published' => 'Y',
  410. 'author' => [
  411. 'id' => 1,
  412. 'name' => 'mariano',
  413. 'posts' => [
  414. [
  415. 'id' => '1',
  416. 'title' => 'First Post',
  417. 'body' => 'First Post Body',
  418. 'author_id' => 1,
  419. 'published' => 'Y',
  420. ],
  421. [
  422. 'id' => '3',
  423. 'title' => 'Third Post',
  424. 'body' => 'Third Post Body',
  425. 'author_id' => 1,
  426. 'published' => 'Y',
  427. ],
  428. ]
  429. ]
  430. ],
  431. [
  432. 'id' => 2,
  433. 'title' => 'Second Article',
  434. 'body' => 'Second Article Body',
  435. 'author_id' => 3,
  436. 'published' => 'Y',
  437. 'author' => [
  438. 'id' => 3,
  439. 'name' => 'larry',
  440. 'posts' => [
  441. [
  442. 'id' => 2,
  443. 'title' => 'Second Post',
  444. 'body' => 'Second Post Body',
  445. 'author_id' => 3,
  446. 'published' => 'Y',
  447. ]
  448. ]
  449. ]
  450. ],
  451. [
  452. 'id' => 3,
  453. 'title' => 'Third Article',
  454. 'body' => 'Third Article Body',
  455. 'author_id' => 1,
  456. 'published' => 'Y',
  457. 'author' => [
  458. 'id' => 1,
  459. 'name' => 'mariano',
  460. 'posts' => [
  461. [
  462. 'id' => '1',
  463. 'title' => 'First Post',
  464. 'body' => 'First Post Body',
  465. 'author_id' => 1,
  466. 'published' => 'Y',
  467. ],
  468. [
  469. 'id' => '3',
  470. 'title' => 'Third Post',
  471. 'body' => 'Third Post Body',
  472. 'author_id' => 1,
  473. 'published' => 'Y',
  474. ],
  475. ]
  476. ]
  477. ],
  478. ];
  479. $this->assertEquals($expected, $results);
  480. }
  481. /**
  482. * Tests that BelongsToMany associations are correctly eager loaded.
  483. * Also that the query object passes the correct parent model keys to the
  484. * association objects in order to perform eager loading with select strategy
  485. *
  486. * @dataProvider strategiesProvider
  487. * @return void
  488. */
  489. public function testBelongsToManyEagerLoadingNoHydration($strategy) {
  490. $table = TableRegistry::get('Articles');
  491. TableRegistry::get('Tags');
  492. TableRegistry::get('ArticlesTags', [
  493. 'table' => 'articles_tags'
  494. ]);
  495. $table->belongsToMany('Tags', ['strategy' => $strategy]);
  496. $query = new Query($this->connection, $table);
  497. $results = $query->select()->contain('Tags')->hydrate(false)->toArray();
  498. $expected = [
  499. [
  500. 'id' => 1,
  501. 'author_id' => 1,
  502. 'title' => 'First Article',
  503. 'body' => 'First Article Body',
  504. 'published' => 'Y',
  505. 'tags' => [
  506. [
  507. 'id' => 1,
  508. 'name' => 'tag1',
  509. '_joinData' => ['article_id' => 1, 'tag_id' => 1]
  510. ],
  511. [
  512. 'id' => 2,
  513. 'name' => 'tag2',
  514. '_joinData' => ['article_id' => 1, 'tag_id' => 2]
  515. ]
  516. ]
  517. ],
  518. [
  519. 'id' => 2,
  520. 'title' => 'Second Article',
  521. 'body' => 'Second Article Body',
  522. 'author_id' => 3,
  523. 'published' => 'Y',
  524. 'tags' => [
  525. [
  526. 'id' => 1,
  527. 'name' => 'tag1',
  528. '_joinData' => ['article_id' => 2, 'tag_id' => 1]
  529. ],
  530. [
  531. 'id' => 3,
  532. 'name' => 'tag3',
  533. '_joinData' => ['article_id' => 2, 'tag_id' => 3]
  534. ]
  535. ]
  536. ],
  537. [
  538. 'id' => 3,
  539. 'title' => 'Third Article',
  540. 'body' => 'Third Article Body',
  541. 'author_id' => 1,
  542. 'published' => 'Y',
  543. 'tags' => [],
  544. ],
  545. ];
  546. $this->assertEquals($expected, $results);
  547. $results = $query->select()
  548. ->contain(['Tags' => ['conditions' => ['Tags.id' => 3]]])
  549. ->hydrate(false)
  550. ->toArray();
  551. $expected = [
  552. [
  553. 'id' => 1,
  554. 'author_id' => 1,
  555. 'title' => 'First Article',
  556. 'body' => 'First Article Body',
  557. 'published' => 'Y',
  558. 'tags' => [],
  559. ],
  560. [
  561. 'id' => 2,
  562. 'title' => 'Second Article',
  563. 'body' => 'Second Article Body',
  564. 'author_id' => 3,
  565. 'published' => 'Y',
  566. 'tags' => [
  567. [
  568. 'id' => 3,
  569. 'name' => 'tag3',
  570. '_joinData' => ['article_id' => 2, 'tag_id' => 3]
  571. ]
  572. ]
  573. ],
  574. [
  575. 'id' => 3,
  576. 'title' => 'Third Article',
  577. 'body' => 'Third Article Body',
  578. 'author_id' => 1,
  579. 'published' => 'Y',
  580. 'tags' => [],
  581. ],
  582. ];
  583. $this->assertEquals($expected, $results);
  584. $this->assertEquals($table->association('Tags')->strategy(), $strategy);
  585. }
  586. /**
  587. * Tests that tables results can be filtered by the result of a HasMany
  588. *
  589. * @return void
  590. */
  591. public function testFilteringByHasManyNoHydration() {
  592. $query = new Query($this->connection, $this->table);
  593. $table = TableRegistry::get('authors');
  594. TableRegistry::get('articles');
  595. $table->hasMany('articles');
  596. $results = $query->repository($table)
  597. ->select()
  598. ->hydrate(false)
  599. ->matching('articles', function ($q) {
  600. return $q->where(['articles.id' => 2]);
  601. })
  602. ->toArray();
  603. $expected = [
  604. [
  605. 'id' => 3,
  606. 'name' => 'larry',
  607. '_matchingData' => [
  608. 'articles' => [
  609. 'id' => 2,
  610. 'title' => 'Second Article',
  611. 'body' => 'Second Article Body',
  612. 'author_id' => 3,
  613. 'published' => 'Y',
  614. ]
  615. ]
  616. ]
  617. ];
  618. $this->assertEquals($expected, $results);
  619. }
  620. /**
  621. * Tests that BelongsToMany associations are correctly eager loaded.
  622. * Also that the query object passes the correct parent model keys to the
  623. * association objects in order to perform eager loading with select strategy
  624. *
  625. * @return void
  626. */
  627. public function testFilteringByBelongsToManyNoHydration() {
  628. $query = new Query($this->connection, $this->table);
  629. $table = TableRegistry::get('Articles');
  630. TableRegistry::get('Tags');
  631. TableRegistry::get('ArticlesTags', [
  632. 'table' => 'articles_tags'
  633. ]);
  634. $table->belongsToMany('Tags');
  635. $results = $query->repository($table)->select()
  636. ->matching('Tags', function ($q) {
  637. return $q->where(['Tags.id' => 3]);
  638. })
  639. ->hydrate(false)
  640. ->toArray();
  641. $expected = [
  642. [
  643. 'id' => 2,
  644. 'author_id' => 3,
  645. 'title' => 'Second Article',
  646. 'body' => 'Second Article Body',
  647. 'published' => 'Y',
  648. '_matchingData' => [
  649. 'Tags' => [
  650. 'id' => 3,
  651. 'name' => 'tag3',
  652. 'articles_tags' => ['article_id' => 2, 'tag_id' => 3]
  653. ]
  654. ]
  655. ]
  656. ];
  657. $this->assertEquals($expected, $results);
  658. $query = new Query($this->connection, $table);
  659. $results = $query->select()
  660. ->matching('Tags', function ($q) {
  661. return $q->where(['Tags.name' => 'tag2']);
  662. })
  663. ->hydrate(false)
  664. ->toArray();
  665. $expected = [
  666. [
  667. 'id' => 1,
  668. 'title' => 'First Article',
  669. 'body' => 'First Article Body',
  670. 'author_id' => 1,
  671. 'published' => 'Y',
  672. '_matchingData' => [
  673. 'Tags' => [
  674. 'id' => 2,
  675. 'name' => 'tag2',
  676. 'articles_tags' => ['article_id' => 1, 'tag_id' => 2]
  677. ]
  678. ]
  679. ]
  680. ];
  681. $this->assertEquals($expected, $results);
  682. }
  683. /**
  684. * Tests that it is possible to filter by deep associations
  685. *
  686. * @return void
  687. */
  688. public function testMatchingDotNotation() {
  689. $query = new Query($this->connection, $this->table);
  690. $table = TableRegistry::get('authors');
  691. TableRegistry::get('articles');
  692. $table->hasMany('articles');
  693. TableRegistry::get('articles')->belongsToMany('tags');
  694. $results = $query->repository($table)
  695. ->select()
  696. ->hydrate(false)
  697. ->matching('articles.tags', function ($q) {
  698. return $q->where(['tags.id' => 2]);
  699. })
  700. ->toArray();
  701. $expected = [
  702. [
  703. 'id' => 1,
  704. 'name' => 'mariano',
  705. '_matchingData' => [
  706. 'tags' => [
  707. 'id' => 2,
  708. 'name' => 'tag2',
  709. 'articles_tags' => [
  710. 'article_id' => 1,
  711. 'tag_id' => 2
  712. ]
  713. ],
  714. 'articles' => [
  715. 'id' => 1,
  716. 'author_id' => 1,
  717. 'title' => 'First Article',
  718. 'body' => 'First Article Body',
  719. 'published' => 'Y'
  720. ]
  721. ]
  722. ]
  723. ];
  724. $this->assertEquals($expected, $results);
  725. }
  726. /**
  727. * Test setResult()
  728. *
  729. * @return void
  730. */
  731. public function testSetResult() {
  732. $query = new Query($this->connection, $this->table);
  733. $stmt = $this->getMock('Cake\Database\StatementInterface');
  734. $results = new ResultSet($query, $stmt);
  735. $query->setResult($results);
  736. $this->assertSame($results, $query->all());
  737. }
  738. /**
  739. * Tests that applying array options to a query will convert them
  740. * to equivalent function calls with the correspondent array values
  741. *
  742. * @return void
  743. */
  744. public function testApplyOptions() {
  745. $options = [
  746. 'fields' => ['field_a', 'field_b'],
  747. 'conditions' => ['field_a' => 1, 'field_b' => 'something'],
  748. 'limit' => 1,
  749. 'order' => ['a' => 'ASC'],
  750. 'offset' => 5,
  751. 'group' => ['field_a'],
  752. 'having' => ['field_a >' => 100],
  753. 'contain' => ['table_a' => ['table_b']],
  754. 'join' => ['table_a' => ['conditions' => ['a > b']]]
  755. ];
  756. $query = new Query($this->connection, $this->table);
  757. $query->applyOptions($options);
  758. $this->assertEquals(['field_a', 'field_b'], $query->clause('select'));
  759. $expected = new QueryExpression($options['conditions'], $this->fooTypeMap);
  760. $result = $query->clause('where');
  761. $this->assertEquals($expected, $result);
  762. $this->assertEquals(1, $query->clause('limit'));
  763. $expected = new QueryExpression(['a > b']);
  764. $expected->typeMap($this->fooTypeMap);
  765. $result = $query->clause('join');
  766. $this->assertEquals([
  767. 'table_a' => ['alias' => 'table_a', 'type' => 'INNER', 'conditions' => $expected]
  768. ], $result);
  769. $expected = new OrderByExpression(['a' => 'ASC']);
  770. $this->assertEquals($expected, $query->clause('order'));
  771. $this->assertEquals(5, $query->clause('offset'));
  772. $this->assertEquals(['field_a'], $query->clause('group'));
  773. $expected = new QueryExpression($options['having']);
  774. $expected->typeMap($this->fooTypeMap);
  775. $this->assertEquals($expected, $query->clause('having'));
  776. $expected = ['table_a' => ['table_b' => []]];
  777. $this->assertEquals($expected, $query->contain());
  778. }
  779. /**
  780. * Test that page is applied after limit.
  781. *
  782. * @return void
  783. */
  784. public function testApplyOptionsPageIsLast() {
  785. $query = new Query($this->connection, $this->table);
  786. $opts = [
  787. 'page' => 3,
  788. 'limit' => 5
  789. ];
  790. $query->applyOptions($opts);
  791. $this->assertEquals(5, $query->clause('limit'));
  792. $this->assertEquals(10, $query->clause('offset'));
  793. }
  794. /**
  795. * ApplyOptions should ignore null values.
  796. *
  797. * @return void
  798. */
  799. public function testApplyOptionsIgnoreNull() {
  800. $options = [
  801. 'fields' => null,
  802. ];
  803. $query = new Query($this->connection, $this->table);
  804. $query->applyOptions($options);
  805. $this->assertEquals([], $query->clause('select'));
  806. }
  807. /**
  808. * Tests getOptions() method
  809. *
  810. * @return void
  811. */
  812. public function testGetOptions() {
  813. $options = ['doABarrelRoll' => true, 'fields' => ['id', 'name']];
  814. $query = new Query($this->connection, $this->table);
  815. $query->applyOptions($options);
  816. $expected = ['doABarrelRoll' => true];
  817. $this->assertEquals($expected, $query->getOptions());
  818. $expected = ['doABarrelRoll' => false, 'doAwesome' => true];
  819. $query->applyOptions($expected);
  820. $this->assertEquals($expected, $query->getOptions());
  821. }
  822. /**
  823. * Tests registering mappers with mapReduce()
  824. *
  825. * @return void
  826. */
  827. public function testMapReduceOnlyMapper() {
  828. $mapper1 = function () {
  829. };
  830. $mapper2 = function () {
  831. };
  832. $query = new Query($this->connection, $this->table);
  833. $this->assertSame($query, $query->mapReduce($mapper1));
  834. $this->assertEquals(
  835. [['mapper' => $mapper1, 'reducer' => null]],
  836. $query->mapReduce()
  837. );
  838. $this->assertEquals($query, $query->mapReduce($mapper2));
  839. $result = $query->mapReduce();
  840. $this->assertSame(
  841. [
  842. ['mapper' => $mapper1, 'reducer' => null],
  843. ['mapper' => $mapper2, 'reducer' => null]
  844. ],
  845. $result
  846. );
  847. }
  848. /**
  849. * Tests registering mappers and reducers with mapReduce()
  850. *
  851. * @return void
  852. */
  853. public function testMapReduceBothMethods() {
  854. $mapper1 = function () {
  855. };
  856. $mapper2 = function () {
  857. };
  858. $reducer1 = function () {
  859. };
  860. $reducer2 = function () {
  861. };
  862. $query = new Query($this->connection, $this->table);
  863. $this->assertSame($query, $query->mapReduce($mapper1, $reducer1));
  864. $this->assertEquals(
  865. [['mapper' => $mapper1, 'reducer' => $reducer1]],
  866. $query->mapReduce()
  867. );
  868. $this->assertSame($query, $query->mapReduce($mapper2, $reducer2));
  869. $this->assertEquals(
  870. [
  871. ['mapper' => $mapper1, 'reducer' => $reducer1],
  872. ['mapper' => $mapper2, 'reducer' => $reducer2]
  873. ],
  874. $query->mapReduce()
  875. );
  876. }
  877. /**
  878. * Tests that it is possible to overwrite previous map reducers
  879. *
  880. * @return void
  881. */
  882. public function testOverwriteMapReduce() {
  883. $mapper1 = function () {
  884. };
  885. $mapper2 = function () {
  886. };
  887. $reducer1 = function () {
  888. };
  889. $reducer2 = function () {
  890. };
  891. $query = new Query($this->connection, $this->table);
  892. $this->assertEquals($query, $query->mapReduce($mapper1, $reducer1));
  893. $this->assertEquals(
  894. [['mapper' => $mapper1, 'reducer' => $reducer1]],
  895. $query->mapReduce()
  896. );
  897. $this->assertEquals($query, $query->mapReduce($mapper2, $reducer2, true));
  898. $this->assertEquals(
  899. [['mapper' => $mapper2, 'reducer' => $reducer2]],
  900. $query->mapReduce()
  901. );
  902. }
  903. /**
  904. * Tests that multiple map reducers can be stacked
  905. *
  906. * @return void
  907. */
  908. public function testResultsAreWrappedInMapReduce() {
  909. $params = [$this->connection, $this->table];
  910. $query = $this->getMock('\Cake\ORM\Query', ['execute'], $params);
  911. $statement = $this->getMock(
  912. '\Database\StatementInterface',
  913. ['fetch', 'closeCursor', 'rowCount']
  914. );
  915. $statement->expects($this->exactly(3))
  916. ->method('fetch')
  917. ->will($this->onConsecutiveCalls(['a' => 1], ['a' => 2], false));
  918. $statement->expects($this->once())
  919. ->method('rowCount')
  920. ->will($this->returnValue(2));
  921. $query->expects($this->once())
  922. ->method('execute')
  923. ->will($this->returnValue($statement));
  924. $query->mapReduce(function ($v, $k, $mr) {
  925. $mr->emit($v['a']);
  926. });
  927. $query->mapReduce(
  928. function ($v, $k, $mr) {
  929. $mr->emitIntermediate($v, $k);
  930. },
  931. function ($v, $k, $mr) {
  932. $mr->emit($v[0] + 1);
  933. }
  934. );
  935. $this->assertEquals([2, 3], iterator_to_array($query->all()));
  936. }
  937. /**
  938. * Tests first() method when the query has not been executed before
  939. *
  940. * @return void
  941. */
  942. public function testFirstDirtyQuery() {
  943. $table = TableRegistry::get('articles', ['table' => 'articles']);
  944. $query = new Query($this->connection, $table);
  945. $result = $query->select(['id'])->hydrate(false)->first();
  946. $this->assertEquals(['id' => 1], $result);
  947. $this->assertEquals(1, $query->clause('limit'));
  948. $result = $query->select(['id'])->first();
  949. $this->assertEquals(['id' => 1], $result);
  950. }
  951. /**
  952. * Tests that first can be called again on an already executed query
  953. *
  954. * @return void
  955. */
  956. public function testFirstCleanQuery() {
  957. $table = TableRegistry::get('articles', ['table' => 'articles']);
  958. $query = new Query($this->connection, $table);
  959. $query->select(['id'])->toArray();
  960. $first = $query->hydrate(false)->first();
  961. $this->assertEquals(['id' => 1], $first);
  962. $this->assertEquals(1, $query->clause('limit'));
  963. }
  964. /**
  965. * Tests that first() will not execute the same query twice
  966. *
  967. * @return void
  968. */
  969. public function testFirstSameResult() {
  970. $table = TableRegistry::get('articles', ['table' => 'articles']);
  971. $query = new Query($this->connection, $table);
  972. $query->select(['id'])->toArray();
  973. $first = $query->hydrate(false)->first();
  974. $resultSet = $query->all();
  975. $this->assertEquals(['id' => 1], $first);
  976. $this->assertSame($resultSet, $query->all());
  977. }
  978. /**
  979. * Tests that first can be called against a query with a mapReduce
  980. *
  981. * @return void
  982. */
  983. public function testFirstMapReduce() {
  984. $map = function ($row, $key, $mapReduce) {
  985. $mapReduce->emitIntermediate($row['id'], 'id');
  986. };
  987. $reduce = function ($values, $key, $mapReduce) {
  988. $mapReduce->emit(array_sum($values));
  989. };
  990. $table = TableRegistry::get('articles', ['table' => 'articles']);
  991. $query = new Query($this->connection, $table);
  992. $query->select(['id'])
  993. ->hydrate(false)
  994. ->mapReduce($map, $reduce);
  995. $first = $query->first();
  996. $this->assertEquals(1, $first);
  997. }
  998. /**
  999. * Testing hydrating a result set into Entity objects
  1000. *
  1001. * @return void
  1002. */
  1003. public function testHydrateSimple() {
  1004. $table = TableRegistry::get('articles', ['table' => 'articles']);
  1005. $query = new Query($this->connection, $table);
  1006. $results = $query->select()->toArray();
  1007. $this->assertCount(3, $results);
  1008. foreach ($results as $r) {
  1009. $this->assertInstanceOf('\Cake\ORM\Entity', $r);
  1010. }
  1011. $first = $results[0];
  1012. $this->assertEquals(1, $first->id);
  1013. $this->assertEquals(1, $first->author_id);
  1014. $this->assertEquals('First Article', $first->title);
  1015. $this->assertEquals('First Article Body', $first->body);
  1016. $this->assertEquals('Y', $first->published);
  1017. }
  1018. /**
  1019. * Tests that has many results are also hydrated correctly
  1020. *
  1021. * @return void
  1022. */
  1023. public function testHydrateHasMany() {
  1024. $table = TableRegistry::get('authors');
  1025. TableRegistry::get('articles');
  1026. $table->hasMany('articles', [
  1027. 'propertyName' => 'articles',
  1028. 'sort' => ['articles.id' => 'asc']
  1029. ]);
  1030. $query = new Query($this->connection, $table);
  1031. $results = $query->select()
  1032. ->contain('articles')
  1033. ->toArray();
  1034. $first = $results[0];
  1035. foreach ($first->articles as $r) {
  1036. $this->assertInstanceOf('\Cake\ORM\Entity', $r);
  1037. }
  1038. $this->assertCount(2, $first->articles);
  1039. $expected = [
  1040. 'id' => 1,
  1041. 'title' => 'First Article',
  1042. 'body' => 'First Article Body',
  1043. 'author_id' => 1,
  1044. 'published' => 'Y',
  1045. ];
  1046. $this->assertEquals($expected, $first->articles[0]->toArray());
  1047. $expected = [
  1048. 'id' => 3,
  1049. 'title' => 'Third Article',
  1050. 'author_id' => 1,
  1051. 'body' => 'Third Article Body',
  1052. 'published' => 'Y',
  1053. ];
  1054. $this->assertEquals($expected, $first->articles[1]->toArray());
  1055. }
  1056. /**
  1057. * Tests that belongsToMany associations are also correctly hydrated
  1058. *
  1059. * @return void
  1060. */
  1061. public function testHydrateBelongsToMany() {
  1062. $table = TableRegistry::get('Articles');
  1063. TableRegistry::get('Tags');
  1064. TableRegistry::get('ArticlesTags', [
  1065. 'table' => 'articles_tags'
  1066. ]);
  1067. $table->belongsToMany('Tags');
  1068. $query = new Query($this->connection, $table);
  1069. $results = $query
  1070. ->select()
  1071. ->contain('Tags')
  1072. ->toArray();
  1073. $first = $results[0];
  1074. foreach ($first->tags as $r) {
  1075. $this->assertInstanceOf('\Cake\ORM\Entity', $r);
  1076. }
  1077. $this->assertCount(2, $first->tags);
  1078. $expected = [
  1079. 'id' => 1,
  1080. 'name' => 'tag1',
  1081. '_joinData' => ['article_id' => 1, 'tag_id' => 1]
  1082. ];
  1083. $this->assertEquals($expected, $first->tags[0]->toArray());
  1084. $expected = [
  1085. 'id' => 2,
  1086. 'name' => 'tag2',
  1087. '_joinData' => ['article_id' => 1, 'tag_id' => 2]
  1088. ];
  1089. $this->assertEquals($expected, $first->tags[1]->toArray());
  1090. }
  1091. /**
  1092. * Tests that belongsTo relations are correctly hydrated
  1093. *
  1094. * @dataProvider internalStategiesProvider
  1095. * @return void
  1096. */
  1097. public function testHydrateBelongsTo($strategy) {
  1098. $table = TableRegistry::get('articles');
  1099. TableRegistry::get('authors');
  1100. $table->belongsTo('authors', ['strategy' => $strategy]);
  1101. $query = new Query($this->connection, $table);
  1102. $results = $query->select()
  1103. ->contain('authors')
  1104. ->order(['articles.id' => 'asc'])
  1105. ->toArray();
  1106. $this->assertCount(3, $results);
  1107. $first = $results[0];
  1108. $this->assertInstanceOf('\Cake\ORM\Entity', $first->author);
  1109. $expected = ['id' => 1, 'name' => 'mariano'];
  1110. $this->assertEquals($expected, $first->author->toArray());
  1111. }
  1112. /**
  1113. * Tests that deeply nested associations are also hydrated correctly
  1114. *
  1115. * @dataProvider internalStategiesProvider
  1116. * @return void
  1117. */
  1118. public function testHydrateDeep($strategy) {
  1119. $table = TableRegistry::get('authors');
  1120. $article = TableRegistry::get('articles');
  1121. $table->hasMany('articles', [
  1122. 'propertyName' => 'articles',
  1123. 'sort' => ['articles.id' => 'asc']
  1124. ]);
  1125. $article->belongsTo('authors', ['strategy' => $strategy]);
  1126. $query = new Query($this->connection, $table);
  1127. $results = $query->select()
  1128. ->contain(['articles' => ['authors']])
  1129. ->toArray();
  1130. $this->assertCount(4, $results);
  1131. $first = $results[0];
  1132. $this->assertInstanceOf('\Cake\ORM\Entity', $first->articles[0]->author);
  1133. $expected = ['id' => 1, 'name' => 'mariano'];
  1134. $this->assertEquals($expected, $first->articles[0]->author->toArray());
  1135. $this->assertTrue(isset($results[3]->articles));
  1136. }
  1137. /**
  1138. * Tests that it is possible to use a custom entity class
  1139. *
  1140. * @return void
  1141. */
  1142. public function testHydrateCustomObject() {
  1143. $class = $this->getMockClass('\Cake\ORM\Entity', ['fakeMethod']);
  1144. $table = TableRegistry::get('articles', [
  1145. 'table' => 'articles',
  1146. 'entityClass' => '\\' . $class
  1147. ]);
  1148. $query = new Query($this->connection, $table);
  1149. $results = $query->select()->toArray();
  1150. $this->assertCount(3, $results);
  1151. foreach ($results as $r) {
  1152. $this->assertInstanceOf($class, $r);
  1153. }
  1154. $first = $results[0];
  1155. $this->assertEquals(1, $first->id);
  1156. $this->assertEquals(1, $first->author_id);
  1157. $this->assertEquals('First Article', $first->title);
  1158. $this->assertEquals('First Article Body', $first->body);
  1159. $this->assertEquals('Y', $first->published);
  1160. }
  1161. /**
  1162. * Tests that has many results are also hydrated correctly
  1163. * when specified a custom entity class
  1164. *
  1165. * @return void
  1166. */
  1167. public function testHydrateHasManyCustomEntity() {
  1168. $authorEntity = $this->getMockClass('\Cake\ORM\Entity', ['foo']);
  1169. $articleEntity = $this->getMockClass('\Cake\ORM\Entity', ['foo']);
  1170. $table = TableRegistry::get('authors', [
  1171. 'entityClass' => '\\' . $authorEntity
  1172. ]);
  1173. TableRegistry::get('articles', [
  1174. 'entityClass' => '\\' . $articleEntity
  1175. ]);
  1176. $table->hasMany('articles', [
  1177. 'propertyName' => 'articles',
  1178. 'sort' => ['articles.id' => 'asc']
  1179. ]);
  1180. $query = new Query($this->connection, $table);
  1181. $results = $query->select()
  1182. ->contain('articles')
  1183. ->toArray();
  1184. $first = $results[0];
  1185. $this->assertInstanceOf($authorEntity, $first);
  1186. foreach ($first->articles as $r) {
  1187. $this->assertInstanceOf($articleEntity, $r);
  1188. }
  1189. $this->assertCount(2, $first->articles);
  1190. $expected = [
  1191. 'id' => 1,
  1192. 'title' => 'First Article',
  1193. 'body' => 'First Article Body',
  1194. 'author_id' => 1,
  1195. 'published' => 'Y',
  1196. ];
  1197. $this->assertEquals($expected, $first->articles[0]->toArray());
  1198. }
  1199. /**
  1200. * Tests that belongsTo relations are correctly hydrated into a custom entity class
  1201. *
  1202. * @return void
  1203. */
  1204. public function testHydrateBelongsToCustomEntity() {
  1205. $authorEntity = $this->getMockClass('\Cake\ORM\Entity', ['foo']);
  1206. $table = TableRegistry::get('articles');
  1207. TableRegistry::get('authors', [
  1208. 'entityClass' => '\\' . $authorEntity
  1209. ]);
  1210. $table->belongsTo('authors');
  1211. $query = new Query($this->connection, $table);
  1212. $results = $query->select()
  1213. ->contain('authors')
  1214. ->order(['articles.id' => 'asc'])
  1215. ->toArray();
  1216. $first = $results[0];
  1217. $this->assertInstanceOf($authorEntity, $first->author);
  1218. }
  1219. /**
  1220. * Test getting counts from queries.
  1221. *
  1222. * @return void
  1223. */
  1224. public function testCount() {
  1225. $table = TableRegistry::get('articles');
  1226. $result = $table->find('all')->count();
  1227. $this->assertSame(3, $result);
  1228. $query = $table->find('all')
  1229. ->where(['id >' => 1])
  1230. ->limit(1);
  1231. $result = $query->count();
  1232. $this->assertSame(2, $result);
  1233. $result = $query->all();
  1234. $this->assertCount(1, $result);
  1235. $this->assertEquals(2, $result->first()->id);
  1236. }
  1237. /**
  1238. * test count with a beforeFind.
  1239. *
  1240. * @return void
  1241. */
  1242. public function testCountBeforeFind() {
  1243. $table = TableRegistry::get('Articles');
  1244. $table->hasMany('Comments');
  1245. $table->eventManager()
  1246. ->attach(function ($event, $query) {
  1247. $query
  1248. ->limit(1)
  1249. ->order(['Articles.title' => 'DESC']);
  1250. }, 'Model.beforeFind');
  1251. $query = $table->find();
  1252. $result = $query->count();
  1253. $this->assertSame(3, $result);
  1254. }
  1255. /**
  1256. * Test that count() returns correct results with group by.
  1257. *
  1258. * @return void
  1259. */
  1260. public function testCountWithGroup() {
  1261. $table = TableRegistry::get('articles');
  1262. $query = $table->find('all');
  1263. $query->select(['author_id', 's' => $query->func()->sum('id')])
  1264. ->group(['author_id']);
  1265. $result = $query->count();
  1266. $this->assertEquals(2, $result);
  1267. }
  1268. /**
  1269. * Tests that it is possible to provide a callback for calculating the count
  1270. * of a query
  1271. *
  1272. * @return void
  1273. */
  1274. public function testCountWithCustomCounter() {
  1275. $table = TableRegistry::get('articles');
  1276. $query = $table->find('all');
  1277. $query
  1278. ->select(['author_id', 's' => $query->func()->sum('id')])
  1279. ->where(['id >' => 2])
  1280. ->group(['author_id'])
  1281. ->counter(function ($q) use ($query) {
  1282. $this->assertNotSame($q, $query);
  1283. return $q->select([], true)->group([], true)->count();
  1284. });
  1285. $result = $query->count();
  1286. $this->assertEquals(1, $result);
  1287. }
  1288. /**
  1289. * Test update method.
  1290. *
  1291. * @return void
  1292. */
  1293. public function testUpdate() {
  1294. $table = TableRegistry::get('articles');
  1295. $result = $table->query()
  1296. ->update()
  1297. ->set(['title' => 'First'])
  1298. ->execute();
  1299. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  1300. $this->assertTrue($result->rowCount() > 0);
  1301. }
  1302. /**
  1303. * Test insert method.
  1304. *
  1305. * @return void
  1306. */
  1307. public function testInsert() {
  1308. $table = TableRegistry::get('articles');
  1309. $result = $table->query()
  1310. ->insert(['title'])
  1311. ->values(['title' => 'First'])
  1312. ->values(['title' => 'Second'])
  1313. ->execute();
  1314. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  1315. $this->assertEquals(2, $result->rowCount());
  1316. }
  1317. /**
  1318. * Test delete method.
  1319. *
  1320. * @return void
  1321. */
  1322. public function testDelete() {
  1323. $table = TableRegistry::get('articles');
  1324. $result = $table->query()
  1325. ->delete()
  1326. ->where(['id >=' => 1])
  1327. ->execute();
  1328. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  1329. $this->assertTrue($result->rowCount() > 0);
  1330. }
  1331. /**
  1332. * Provides a list of collection methods that can be proxied
  1333. * from the query
  1334. *
  1335. * @return array
  1336. */
  1337. public function collectionMethodsProvider() {
  1338. $identity = function ($a) {
  1339. return $a;
  1340. };
  1341. return [
  1342. ['filter', $identity],
  1343. ['reject', $identity],
  1344. ['every', $identity],
  1345. ['some', $identity],
  1346. ['contains', $identity],
  1347. ['map', $identity],
  1348. ['reduce', $identity],
  1349. ['extract', $identity],
  1350. ['max', $identity],
  1351. ['min', $identity],
  1352. ['sortBy', $identity],
  1353. ['groupBy', $identity],
  1354. ['countBy', $identity],
  1355. ['shuffle', $identity],
  1356. ['sample', $identity],
  1357. ['take', 1],
  1358. ['append', new \ArrayIterator],
  1359. ['compile', 1],
  1360. ];
  1361. }
  1362. /**
  1363. * Tests that query can proxy collection methods
  1364. *
  1365. * @dataProvider collectionMethodsProvider
  1366. * @return void
  1367. */
  1368. public function testCollectionProxy($method, $arg) {
  1369. $query = $this->getMock(
  1370. '\Cake\ORM\Query', ['all'],
  1371. [$this->connection, $this->table]
  1372. );
  1373. $query->select();
  1374. $resultSet = $this->getMock('\Cake\ORM\ResultSet', [], [$query, null]);
  1375. $query->expects($this->once())
  1376. ->method('all')
  1377. ->will($this->returnValue($resultSet));
  1378. $resultSet->expects($this->once())
  1379. ->method($method)
  1380. ->with($arg, 'extra')
  1381. ->will($this->returnValue(new \Cake\Collection\Collection([])));
  1382. $this->assertInstanceOf(
  1383. '\Cake\Collection\Collection',
  1384. $query->{$method}($arg, 'extra')
  1385. );
  1386. }
  1387. /**
  1388. * Tests that calling an inexistent method in query throws an
  1389. * exception
  1390. *
  1391. * @expectedException \BadMethodCallException
  1392. * @expectedExceptionMessage Unknown method "derpFilter"
  1393. * @return void
  1394. */
  1395. public function testCollectionProxyBadMethod() {
  1396. TableRegistry::get('articles')->find('all')->derpFilter();
  1397. }
  1398. /**
  1399. * cache() should fail on non select queries.
  1400. *
  1401. * @expectedException \RuntimeException
  1402. * @return void
  1403. */
  1404. public function testCacheErrorOnNonSelect() {
  1405. $table = TableRegistry::get('articles', ['table' => 'articles']);
  1406. $query = new Query($this->connection, $table);
  1407. $query->insert(['test']);
  1408. $query->cache('my_key');
  1409. }
  1410. /**
  1411. * Integration test for query caching.
  1412. *
  1413. * @return void
  1414. */
  1415. public function testCacheReadIntegration() {
  1416. $query = $this->getMock(
  1417. '\Cake\ORM\Query', ['execute'],
  1418. [$this->connection, $this->table]
  1419. );
  1420. $resultSet = $this->getMock('\Cake\ORM\ResultSet', [], [$query, null]);
  1421. $query->expects($this->never())
  1422. ->method('execute');
  1423. $cacher = $this->getMock('Cake\Cache\CacheEngine');
  1424. $cacher->expects($this->once())
  1425. ->method('read')
  1426. ->with('my_key')
  1427. ->will($this->returnValue($resultSet));
  1428. $query->cache('my_key', $cacher)
  1429. ->where(['id' => 1]);
  1430. $results = $query->all();
  1431. $this->assertSame($resultSet, $results);
  1432. }
  1433. /**
  1434. * Integration test for query caching.
  1435. *
  1436. * @return void
  1437. */
  1438. public function testCacheWriteIntegration() {
  1439. $table = TableRegistry::get('Articles');
  1440. $query = new Query($this->connection, $table);
  1441. $query->select(['id', 'title']);
  1442. $cacher = $this->getMock('Cake\Cache\CacheEngine');
  1443. $cacher->expects($this->once())
  1444. ->method('write')
  1445. ->with(
  1446. 'my_key',
  1447. $this->isInstanceOf('Cake\Datasource\ResultSetInterface')
  1448. );
  1449. $query->cache('my_key', $cacher)
  1450. ->where(['id' => 1]);
  1451. $query->all();
  1452. }
  1453. /**
  1454. * Integration test to show filtering associations using contain and a closure
  1455. *
  1456. * @return void
  1457. */
  1458. public function testContainWithClosure() {
  1459. $table = TableRegistry::get('authors');
  1460. $table->hasMany('articles');
  1461. $query = new Query($this->connection, $table);
  1462. $query
  1463. ->select()
  1464. ->contain(['articles' => function ($q) {
  1465. return $q->where(['articles.id' => 1]);
  1466. }]);
  1467. $ids = [];
  1468. foreach ($query as $entity) {
  1469. foreach ((array)$entity->articles as $article) {
  1470. $ids[] = $article->id;
  1471. }
  1472. }
  1473. $this->assertEquals([1], array_unique($ids));
  1474. }
  1475. /**
  1476. * Tests the formatResults method
  1477. *
  1478. * @return void
  1479. */
  1480. public function testFormatResults() {
  1481. $callback1 = function () {
  1482. };
  1483. $callback2 = function () {
  1484. };
  1485. $table = TableRegistry::get('authors');
  1486. $query = new Query($this->connection, $table);
  1487. $this->assertSame($query, $query->formatResults($callback1));
  1488. $this->assertSame([$callback1], $query->formatResults());
  1489. $this->assertSame($query, $query->formatResults($callback2));
  1490. $this->assertSame([$callback1, $callback2], $query->formatResults());
  1491. $query->formatResults($callback2, true);
  1492. $this->assertSame([$callback2], $query->formatResults());
  1493. $query->formatResults(null, true);
  1494. $this->assertSame([], $query->formatResults());
  1495. $query->formatResults($callback1);
  1496. $query->formatResults($callback2, $query::PREPEND);
  1497. $this->assertSame([$callback2, $callback1], $query->formatResults());
  1498. }
  1499. /**
  1500. * Test fetching results from a qurey with a custom formatter
  1501. *
  1502. * @return void
  1503. */
  1504. public function testQueryWithFormatter() {
  1505. $table = TableRegistry::get('authors');
  1506. $query = new Query($this->connection, $table);
  1507. $query->select()->formatResults(function ($results, $q) use ($query) {
  1508. $this->assertSame($query, $q);
  1509. $this->assertInstanceOf('\Cake\ORM\ResultSet', $results);
  1510. return $results->indexBy('id');
  1511. });
  1512. $this->assertEquals([1, 2, 3, 4], array_keys($query->toArray()));
  1513. }
  1514. /**
  1515. * Test fetching results from a qurey with a two custom formatters
  1516. *
  1517. * @return void
  1518. */
  1519. public function testQueryWithStackedFormatters() {
  1520. $table = TableRegistry::get('authors');
  1521. $query = new Query($this->connection, $table);
  1522. $query->select()->formatResults(function ($results, $q) use ($query) {
  1523. $this->assertSame($query, $q);
  1524. $this->assertInstanceOf('\Cake\ORM\ResultSet', $results);
  1525. return $results->indexBy('id');
  1526. });
  1527. $query->formatResults(function ($results) {
  1528. return $results->extract('name');
  1529. });
  1530. $expected = [
  1531. 1 => 'mariano',
  1532. 2 => 'nate',
  1533. 3 => 'larry',
  1534. 4 => 'garrett'
  1535. ];
  1536. $this->assertEquals($expected, $query->toArray());
  1537. }
  1538. /**
  1539. * Tests that getting results from a query having a contained association
  1540. * will no attach joins twice if count() is called on it afterwards
  1541. *
  1542. * @return void
  1543. */
  1544. public function testCountWithContainCallingAll() {
  1545. $table = TableRegistry::get('articles');
  1546. $table->belongsTo('authors');
  1547. $query = $table->find()
  1548. ->select(['id', 'title'])
  1549. ->contain('authors')
  1550. ->limit(2);
  1551. $results = $query->all();
  1552. $this->assertCount(2, $results);
  1553. $this->assertEquals(3, $query->count());
  1554. }
  1555. /**
  1556. * Tests that it is possible to apply formatters inside the query builder
  1557. * for belongsTo associations
  1558. *
  1559. * @return void
  1560. */
  1561. public function testFormatBelongsToRecords() {
  1562. $table = TableRegistry::get('articles');
  1563. $table->belongsTo('authors');
  1564. $query = $table->find()
  1565. ->contain(['authors' => function ($q) {
  1566. return $q
  1567. ->formatResults(function ($authors) {
  1568. return $authors->map(function ($author) {
  1569. $author->idCopy = $author->id;
  1570. return $author;
  1571. });
  1572. })
  1573. ->formatResults(function ($authors) {
  1574. return $authors->map(function ($author) {
  1575. $author->idCopy = $author->idCopy + 2;
  1576. return $author;
  1577. });
  1578. });
  1579. }]);
  1580. $query->formatResults(function ($results) {
  1581. return $results->combine('id', 'author.idCopy');
  1582. });
  1583. $results = $query->toArray();
  1584. $expected = [1 => 3, 2 => 5, 3 => 3];
  1585. $this->assertEquals($expected, $results);
  1586. }
  1587. /**
  1588. * Tests it is possible to apply formatters to deep relations.
  1589. *
  1590. * @return void
  1591. */
  1592. public function testFormatDeepAssocationRecords() {
  1593. $table = TableRegistry::get('ArticlesTags');
  1594. $table->belongsTo('Articles');
  1595. $table->association('Articles')->target()->belongsTo('Authors');
  1596. $builder = function ($q) {
  1597. return $q
  1598. ->formatResults(function ($results) {
  1599. return $results->map(function ($result) {
  1600. $result->idCopy = $result->id;
  1601. return $result;
  1602. });
  1603. })
  1604. ->formatResults(function ($results) {
  1605. return $results->map(function ($result) {
  1606. $result->idCopy = $result->idCopy + 2;
  1607. return $result;
  1608. });
  1609. });
  1610. };
  1611. $query = $table->find()
  1612. ->contain(['Articles' => $builder, 'Articles.Authors' => $builder])
  1613. ->order(['Articles.id' => 'ASC']);
  1614. $query->formatResults(function ($results) {
  1615. return $results->map(function ($row) {
  1616. return sprintf(
  1617. '%s - %s - %s',
  1618. $row->tag_id,
  1619. $row->article->idCopy,
  1620. $row->article->author->idCopy
  1621. );
  1622. });
  1623. });
  1624. $expected = ['1 - 3 - 3', '2 - 3 - 3', '1 - 4 - 5', '3 - 4 - 5'];
  1625. $this->assertEquals($expected, $query->toArray());
  1626. }
  1627. /**
  1628. * Tests that formatters cna be applied to deep associations that are fetched using
  1629. * additional queries
  1630. *
  1631. * @return void
  1632. */
  1633. public function testFormatDeepDistantAssociationRecords() {
  1634. $table = TableRegistry::get('authors');
  1635. $table->hasMany('articles');
  1636. $articles = $table->association('articles')->target();
  1637. $articles->hasMany('articlesTags');
  1638. $articles->association('articlesTags')->target()->belongsTo('tags');
  1639. $query = $table->find()->contain(['articles.articlesTags.tags' => function ($q) {
  1640. return $q->formatResults(function ($results) {
  1641. return $results->map(function ($tag) {
  1642. $tag->name .= ' - visited';
  1643. return $tag;
  1644. });
  1645. });
  1646. }]);
  1647. $query->mapReduce(function ($row, $key, $mr) {
  1648. foreach ((array)$row->articles as $article) {
  1649. foreach ((array)$article->articles_tags as $articleTag) {
  1650. $mr->emit($articleTag->tag->name);
  1651. }
  1652. }
  1653. });
  1654. $expected = ['tag1 - visited', 'tag2 - visited', 'tag1 - visited', 'tag3 - visited'];
  1655. $this->assertEquals($expected, $query->toArray());
  1656. }
  1657. /**
  1658. * Tests that custom finders are applied to associations when using the proxies
  1659. *
  1660. * @return void
  1661. */
  1662. public function testCustomFinderInBelongsTo() {
  1663. $table = TableRegistry::get('ArticlesTags');
  1664. $table->belongsTo('Articles', [
  1665. 'className' => 'TestApp\Model\Table\ArticlesTable',
  1666. 'finder' => 'published'
  1667. ]);
  1668. $result = $table->find()->contain('Articles');
  1669. $this->assertCount(4, $result->extract('article')->filter()->toArray());
  1670. $table->Articles->updateAll(['published' => 'N'], ['1 = 1']);
  1671. $result = $table->find()->contain('Articles');
  1672. $this->assertCount(0, $result->extract('article')->filter()->toArray());
  1673. }
  1674. /**
  1675. * Tests that it is possible to attach more association when using a query
  1676. * builder for other associations
  1677. *
  1678. * @return void
  1679. */
  1680. public function testContainInAssociationQuery() {
  1681. $table = TableRegistry::get('ArticlesTags');
  1682. $table->belongsTo('Articles');
  1683. $table->association('Articles')->target()->belongsTo('Authors');
  1684. $query = $table->find()
  1685. ->order(['Articles.id' => 'ASC'])
  1686. ->contain(['Articles' => function ($q) {
  1687. return $q->contain('Authors');
  1688. }]);
  1689. $results = $query->extract('article.author.name')->toArray();
  1690. $expected = ['mariano', 'mariano', 'larry', 'larry'];
  1691. $this->assertEquals($expected, $results);
  1692. }
  1693. /**
  1694. * Tests that it is possible to apply more `matching` conditions inside query
  1695. * builders for associations
  1696. *
  1697. * @return void
  1698. */
  1699. public function testContainInAssociationMatching() {
  1700. $table = TableRegistry::get('authors');
  1701. $table->hasMany('articles');
  1702. $articles = $table->association('articles')->target();
  1703. $articles->hasMany('articlesTags');
  1704. $articles->association('articlesTags')->target()->belongsTo('tags');
  1705. $query = $table->find()->matching('articles.articlesTags', function ($q) {
  1706. return $q->matching('tags', function ($q) {
  1707. return $q->where(['tags.name' => 'tag3']);
  1708. });
  1709. });
  1710. $results = $query->toArray();
  1711. $this->assertCount(1, $results);
  1712. $this->assertEquals('tag3', $results[0]->_matchingData['tags']->name);
  1713. }
  1714. /**
  1715. * Tests __debugInfo
  1716. *
  1717. * @return void
  1718. */
  1719. public function testDebugInfo() {
  1720. $table = TableRegistry::get('authors');
  1721. $table->hasMany('articles');
  1722. $query = $table->find()
  1723. ->where(['id > ' => 1])
  1724. ->bufferResults(false)
  1725. ->hydrate(false)
  1726. ->matching('articles')
  1727. ->applyOptions(['foo' => 'bar'])
  1728. ->formatResults(function ($results) {
  1729. return $results;
  1730. })
  1731. ->mapReduce(function ($item, $key, $mr) {
  1732. $mr->emit($item);
  1733. });
  1734. $expected = [
  1735. 'sql' => $query->sql(),
  1736. 'params' => $query->valueBinder()->bindings(),
  1737. 'defaultTypes' => [
  1738. 'authors.id' => 'integer',
  1739. 'id' => 'integer',
  1740. 'authors.name' => 'string',
  1741. 'name' => 'string'
  1742. ],
  1743. 'decorators' => 0,
  1744. 'executed' => false,
  1745. 'hydrate' => false,
  1746. 'buffered' => false,
  1747. 'formatters' => 1,
  1748. 'mapReducers' => 1,
  1749. 'contain' => [],
  1750. 'matching' => [
  1751. 'articles' => [
  1752. 'queryBuilder' => null,
  1753. 'matching' => true
  1754. ]
  1755. ],
  1756. 'extraOptions' => ['foo' => 'bar'],
  1757. 'repository' => $table
  1758. ];
  1759. $this->assertSame($expected, $query->__debugInfo());
  1760. }
  1761. /**
  1762. * Tests that the eagerLoaded function works and is transmitted correctly to eagerly
  1763. * loaded associations
  1764. *
  1765. * @return void
  1766. */
  1767. public function testEagerLoaded() {
  1768. $table = TableRegistry::get('authors');
  1769. $table->hasMany('articles');
  1770. $query = $table->find()->contain(['articles' => function ($q) {
  1771. $this->assertTrue($q->eagerLoaded());
  1772. return $q;
  1773. }]);
  1774. $this->assertFalse($query->eagerLoaded());
  1775. $table->eventManager()->attach(function ($e, $q, $o, $primary) {
  1776. $this->assertTrue($primary);
  1777. }, 'Model.beforeFind');
  1778. TableRegistry::get('articles')
  1779. ->eventManager()->attach(function ($e, $q, $o, $primary) {
  1780. $this->assertFalse($primary);
  1781. }, 'Model.beforeFind');
  1782. $query->all();
  1783. }
  1784. /**
  1785. * Tests that columns from manual joins are also contained in the result set
  1786. *
  1787. * @return void
  1788. */
  1789. public function testColumnsFromJoin() {
  1790. $table = TableRegistry::get('articles');
  1791. $results = $table->find()
  1792. ->select(['title', 'person.name'])
  1793. ->join([
  1794. 'person' => [
  1795. 'table' => 'authors',
  1796. 'conditions' => ['person.id = articles.author_id']
  1797. ]
  1798. ])
  1799. ->order(['articles.id' => 'ASC'])
  1800. ->hydrate(false)
  1801. ->toArray();
  1802. $expected = [
  1803. ['title' => 'First Article', 'person' => ['name' => 'mariano']],
  1804. ['title' => 'Second Article', 'person' => ['name' => 'larry']],
  1805. ['title' => 'Third Article', 'person' => ['name' => 'mariano']],
  1806. ];
  1807. $this->assertSame($expected, $results);
  1808. }
  1809. /**
  1810. * Tests that it is possible to use the same association aliases in the association
  1811. * chain for contain
  1812. *
  1813. * @dataProvider internalStategiesProvider
  1814. * @return void
  1815. */
  1816. public function testRepeatedAssociationAliases($strategy) {
  1817. $table = TableRegistry::get('ArticlesTags');
  1818. $table->belongsTo('Articles', ['strategy' => $strategy]);
  1819. $table->belongsTo('Tags', ['strategy' => $strategy]);
  1820. TableRegistry::get('Tags')->belongsToMany('Articles');
  1821. $results = $table
  1822. ->find()
  1823. ->contain(['Articles', 'Tags.Articles'])
  1824. ->hydrate(false)
  1825. ->toArray();
  1826. $this->assertNotEmpty($results[0]['tag']['articles']);
  1827. $this->assertNotEmpty($results[0]['article']);
  1828. $this->assertNotEmpty($results[1]['tag']['articles']);
  1829. $this->assertNotEmpty($results[1]['article']);
  1830. $this->assertNotEmpty($results[2]['tag']['articles']);
  1831. $this->assertNotEmpty($results[2]['article']);
  1832. }
  1833. /**
  1834. * Tests that it is not allowed to use matching on an association
  1835. * that is already added to containments.
  1836. *
  1837. * @expectedException \RuntimeException
  1838. * @expectedExceptionMessage Cannot use "matching" on "Authors" as there is another association with the same alias
  1839. * @return void
  1840. */
  1841. public function testConflitingAliases() {
  1842. $this->markTestIncomplete('Needs an actual conflicting case');
  1843. $table = TableRegistry::get('ArticlesTags');
  1844. $table->belongsTo('Articles')->target()->belongsTo('Authors');
  1845. $table->belongsTo('Tags');
  1846. $table->Tags->target()->hasOne('Authors');
  1847. $table->find()
  1848. ->contain(['Articles.Authors'])
  1849. ->matching('Tags.Authors')
  1850. ->sql();
  1851. }
  1852. /**
  1853. * Tests that a hasOne association using the select strategy will still have the
  1854. * key present in the results when no match is found
  1855. *
  1856. * @return void
  1857. */
  1858. public function testAssociationKeyPresent() {
  1859. $table = TableRegistry::get('Articles');
  1860. $table->hasOne('ArticlesTags', ['strategy' => 'select']);
  1861. $article = $table->find()->where(['id' => 3])
  1862. ->hydrate(false)
  1863. ->contain('ArticlesTags')
  1864. ->first();
  1865. $this->assertNull($article['articles_tag']);
  1866. }
  1867. /**
  1868. * Tests that queries can be serialized to JSON to get the results
  1869. *
  1870. * @return void
  1871. */
  1872. public function testJsonSerialize() {
  1873. $table = TableRegistry::get('Articles');
  1874. $this->assertEquals(
  1875. json_encode($table->find()),
  1876. json_encode($table->find()->toArray())
  1877. );
  1878. }
  1879. /**
  1880. * Test that addFields() works in the basic case.
  1881. *
  1882. * @return void
  1883. */
  1884. public function testAutoFields() {
  1885. $table = TableRegistry::get('Articles');
  1886. $result = $table->find('all')
  1887. ->select(['myField' => '(SELECT 20)'])
  1888. ->autoFields(true)
  1889. ->hydrate(false)
  1890. ->first();
  1891. $this->assertArrayHasKey('myField', $result);
  1892. $this->assertArrayHasKey('id', $result);
  1893. $this->assertArrayHasKey('title', $result);
  1894. }
  1895. /**
  1896. * Test autoFields with auto fields.
  1897. *
  1898. * @return void
  1899. */
  1900. public function testAutoFieldsWithAssociations() {
  1901. $table = TableRegistry::get('Articles');
  1902. $table->belongsTo('Authors');
  1903. $result = $table->find()
  1904. ->select(['myField' => '(SELECT 2 + 2)'])
  1905. ->autoFields(true)
  1906. ->hydrate(false)
  1907. ->contain('Authors')
  1908. ->first();
  1909. $this->assertArrayHasKey('myField', $result);
  1910. $this->assertArrayHasKey('title', $result);
  1911. $this->assertArrayHasKey('author', $result);
  1912. $this->assertNotNull($result['author']);
  1913. $this->assertArrayHasKey('name', $result['author']);
  1914. }
  1915. /**
  1916. * Test autoFields in contain query builder
  1917. *
  1918. * @return void
  1919. */
  1920. public function testAutoFieldsWithContainQueryBuilder() {
  1921. $table = TableRegistry::get('Articles');
  1922. $table->belongsTo('Authors');
  1923. $result = $table->find()
  1924. ->select(['myField' => '(SELECT 2 + 2)'])
  1925. ->autoFields(true)
  1926. ->hydrate(false)
  1927. ->contain(['Authors' => function ($q) {
  1928. return $q->select(['compute' => '(SELECT 2 + 20)'])
  1929. ->autoFields(true);
  1930. }])
  1931. ->first();
  1932. $this->assertArrayHasKey('myField', $result);
  1933. $this->assertArrayHasKey('title', $result);
  1934. $this->assertArrayHasKey('author', $result);
  1935. $this->assertNotNull($result['author']);
  1936. $this->assertArrayHasKey('name', $result['author']);
  1937. $this->assertArrayHasKey('compute', $result);
  1938. }
  1939. /**
  1940. * Test that autofields works with count()
  1941. *
  1942. * @return void
  1943. */
  1944. public function testAutoFieldsCount() {
  1945. $table = TableRegistry::get('Articles');
  1946. $result = $table->find()
  1947. ->select(['myField' => '(SELECT (2 + 2))'])
  1948. ->autoFields(true)
  1949. ->count();
  1950. $this->assertEquals(3, $result);
  1951. }
  1952. /**
  1953. * test that cleanCopy makes a cleaned up clone.
  1954. *
  1955. * @return void
  1956. */
  1957. public function testCleanCopy() {
  1958. $table = TableRegistry::get('Articles');
  1959. $table->hasMany('Comments');
  1960. $query = $table->find();
  1961. $query->offset(10)
  1962. ->limit(1)
  1963. ->order(['Articles.id' => 'DESC'])
  1964. ->contain(['Comments']);
  1965. $copy = $query->cleanCopy();
  1966. $this->assertNotSame($copy, $query);
  1967. $this->assertNull($copy->clause('offset'));
  1968. $this->assertNull($copy->clause('limit'));
  1969. $this->assertNull($copy->clause('order'));
  1970. }
  1971. /**
  1972. * test that cleanCopy makes a cleaned up clone with a beforeFind.
  1973. *
  1974. * @return void
  1975. */
  1976. public function testCleanCopyBeforeFind() {
  1977. $table = TableRegistry::get('Articles');
  1978. $table->hasMany('Comments');
  1979. $table->eventManager()
  1980. ->attach(function ($event, $query) {
  1981. $query
  1982. ->limit(5)
  1983. ->order(['Articles.title' => 'DESC']);
  1984. }, 'Model.beforeFind');
  1985. $query = $table->find();
  1986. $query->offset(10)
  1987. ->limit(1)
  1988. ->order(['Articles.id' => 'DESC'])
  1989. ->contain(['Comments']);
  1990. $copy = $query->cleanCopy();
  1991. $this->assertNotSame($copy, $query);
  1992. $this->assertNull($copy->clause('offset'));
  1993. $this->assertNull($copy->clause('limit'));
  1994. $this->assertNull($copy->clause('order'));
  1995. }
  1996. /**
  1997. * Test that finder options sent through via contain are sent to custom finder.
  1998. *
  1999. * @return void
  2000. */
  2001. public function testContainFinderCanSpecifyOptions() {
  2002. $table = TableRegistry::get('Articles');
  2003. $table->belongsTo(
  2004. 'Authors',
  2005. ['className' => 'TestApp\Model\Table\AuthorsTable']
  2006. );
  2007. $authorId = 1;
  2008. $resultWithoutAuthor = $table->find('all')
  2009. ->where(['Articles.author_id' => $authorId])
  2010. ->contain([
  2011. 'Authors' => [
  2012. 'finder' => ['byAuthor' => ['author_id' => 2]]
  2013. ]
  2014. ]);
  2015. $resultWithAuthor = $table->find('all')
  2016. ->where(['Articles.author_id' => $authorId])
  2017. ->contain([
  2018. 'Authors' => [
  2019. 'finder' => ['byAuthor' => ['author_id' => $authorId]]
  2020. ]
  2021. ]);
  2022. $this->assertEmpty($resultWithoutAuthor->first()['author']);
  2023. $this->assertEquals($authorId, $resultWithAuthor->first()['author']['id']);
  2024. }
  2025. /**
  2026. * Tests that it is possible to bind arguments to a query and it will return the right
  2027. * results
  2028. *
  2029. * @return void
  2030. */
  2031. public function testCustomBindings() {
  2032. $table = TableRegistry::get('Articles');
  2033. $query = $table->find()->where(['id >' => 1]);
  2034. $query->where(function ($exp) {
  2035. return $exp->add('author_id = :author');
  2036. });
  2037. $query->bind(':author', 1, 'integer');
  2038. $this->assertEquals(1, $query->count());
  2039. $this->assertEquals(3, $query->first()->id);
  2040. }
  2041. /**
  2042. * Tests that it is possible to pass a custom join type for an association when
  2043. * using contain
  2044. *
  2045. * @return void
  2046. */
  2047. public function testContainWithCustomJoinType() {
  2048. $table = TableRegistry::get('Articles');
  2049. $table->belongsTo('Authors');
  2050. $articles = $table->find()
  2051. ->contain([
  2052. 'Authors' => [
  2053. 'joinType' => 'inner',
  2054. 'conditions' => ['Authors.id' => 3]
  2055. ]
  2056. ])
  2057. ->toArray();
  2058. $this->assertCount(1, $articles);
  2059. $this->assertEquals(3, $articles[0]->author->id);
  2060. }
  2061. /**
  2062. * Tests that it is possible to override the contain strategy using the
  2063. * containments array. In this case, no inner join will be made and for that
  2064. * reason, the parent association will not be filtered as the strategy changed
  2065. * from join to select.
  2066. *
  2067. * @return void
  2068. */
  2069. public function testContainWithStrategyOverride() {
  2070. $table = TableRegistry::get('Articles');
  2071. $table->belongsTo('Authors', [
  2072. 'joinType' => 'INNER'
  2073. ]);
  2074. $articles = $table->find()
  2075. ->contain([
  2076. 'Authors' => [
  2077. 'strategy' => 'select',
  2078. 'conditions' => ['Authors.id' => 3]
  2079. ]
  2080. ])
  2081. ->toArray();
  2082. $this->assertCount(3, $articles);
  2083. $this->assertEquals(3, $articles[1]->author->id);
  2084. $this->assertNull($articles[0]->author);
  2085. $this->assertNull($articles[2]->author);
  2086. }
  2087. /**
  2088. * Tests that it is possible to call matching and contain on the same
  2089. * association.
  2090. *
  2091. * @return void
  2092. */
  2093. public function testMatchingWithContain() {
  2094. $query = new Query($this->connection, $this->table);
  2095. $table = TableRegistry::get('authors');
  2096. $table->hasMany('articles');
  2097. TableRegistry::get('articles')->belongsToMany('tags');
  2098. $result = $query->repository($table)
  2099. ->select()
  2100. ->matching('articles.tags', function ($q) {
  2101. return $q->where(['tags.id' => 2]);
  2102. })
  2103. ->contain('articles')
  2104. ->first();
  2105. $this->assertEquals(1, $result->id);
  2106. $this->assertCount(2, $result->articles);
  2107. $this->assertEquals(2, $result->_matchingData['tags']->id);
  2108. }
  2109. }