QueryTest.php 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177
  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. 'articles' => [
  608. 'id' => 2,
  609. 'title' => 'Second Article',
  610. 'body' => 'Second Article Body',
  611. 'author_id' => 3,
  612. 'published' => 'Y',
  613. ]
  614. ]
  615. ];
  616. $this->assertEquals($expected, $results);
  617. }
  618. /**
  619. * Tests that BelongsToMany associations are correctly eager loaded.
  620. * Also that the query object passes the correct parent model keys to the
  621. * association objects in order to perform eager loading with select strategy
  622. *
  623. * @return void
  624. */
  625. public function testFilteringByBelongsToManyNoHydration() {
  626. $query = new Query($this->connection, $this->table);
  627. $table = TableRegistry::get('Articles');
  628. TableRegistry::get('Tags');
  629. TableRegistry::get('ArticlesTags', [
  630. 'table' => 'articles_tags'
  631. ]);
  632. $table->belongsToMany('Tags');
  633. $results = $query->repository($table)->select()
  634. ->matching('Tags', function ($q) {
  635. return $q->where(['Tags.id' => 3]);
  636. })
  637. ->hydrate(false)
  638. ->toArray();
  639. $expected = [
  640. [
  641. 'id' => 2,
  642. 'author_id' => 3,
  643. 'title' => 'Second Article',
  644. 'body' => 'Second Article Body',
  645. 'published' => 'Y',
  646. 'tags' => [
  647. 'id' => 3,
  648. 'name' => 'tag3',
  649. '_joinData' => ['article_id' => 2, 'tag_id' => 3]
  650. ]
  651. ]
  652. ];
  653. $this->assertEquals($expected, $results);
  654. $query = new Query($this->connection, $table);
  655. $results = $query->select()
  656. ->matching('Tags', function ($q) {
  657. return $q->where(['Tags.name' => 'tag2']);
  658. })
  659. ->hydrate(false)
  660. ->toArray();
  661. $expected = [
  662. [
  663. 'id' => 1,
  664. 'title' => 'First Article',
  665. 'body' => 'First Article Body',
  666. 'author_id' => 1,
  667. 'published' => 'Y',
  668. 'tags' => [
  669. 'id' => 2,
  670. 'name' => 'tag2',
  671. '_joinData' => ['article_id' => 1, 'tag_id' => 2]
  672. ]
  673. ]
  674. ];
  675. $this->assertEquals($expected, $results);
  676. }
  677. /**
  678. * Tests that it is possible to filter by deep associations
  679. *
  680. * @return void
  681. */
  682. public function testMatchingDotNotation() {
  683. $query = new Query($this->connection, $this->table);
  684. $table = TableRegistry::get('authors');
  685. TableRegistry::get('articles');
  686. $table->hasMany('articles');
  687. TableRegistry::get('articles')->belongsToMany('tags');
  688. $results = $query->repository($table)
  689. ->select()
  690. ->hydrate(false)
  691. ->matching('articles.tags', function ($q) {
  692. return $q->where(['tags.id' => 2]);
  693. })
  694. ->toArray();
  695. $expected = [
  696. [
  697. 'id' => 1,
  698. 'name' => 'mariano',
  699. 'articles' => [
  700. 'id' => 1,
  701. 'title' => 'First Article',
  702. 'body' => 'First Article Body',
  703. 'author_id' => 1,
  704. 'published' => 'Y',
  705. 'tags' => [
  706. 'id' => 2,
  707. 'name' => 'tag2',
  708. '_joinData' => ['article_id' => 1, 'tag_id' => 2]
  709. ]
  710. ]
  711. ]
  712. ];
  713. $this->assertEquals($expected, $results);
  714. }
  715. /**
  716. * Test setResult()
  717. *
  718. * @return void
  719. */
  720. public function testSetResult() {
  721. $query = new Query($this->connection, $this->table);
  722. $stmt = $this->getMock('Cake\Database\StatementInterface');
  723. $results = new ResultSet($query, $stmt);
  724. $query->setResult($results);
  725. $this->assertSame($results, $query->all());
  726. }
  727. /**
  728. * Tests that applying array options to a query will convert them
  729. * to equivalent function calls with the correspondent array values
  730. *
  731. * @return void
  732. */
  733. public function testApplyOptions() {
  734. $options = [
  735. 'fields' => ['field_a', 'field_b'],
  736. 'conditions' => ['field_a' => 1, 'field_b' => 'something'],
  737. 'limit' => 1,
  738. 'order' => ['a' => 'ASC'],
  739. 'offset' => 5,
  740. 'group' => ['field_a'],
  741. 'having' => ['field_a >' => 100],
  742. 'contain' => ['table_a' => ['table_b']],
  743. 'join' => ['table_a' => ['conditions' => ['a > b']]]
  744. ];
  745. $query = new Query($this->connection, $this->table);
  746. $query->applyOptions($options);
  747. $this->assertEquals(['field_a', 'field_b'], $query->clause('select'));
  748. $expected = new QueryExpression($options['conditions'], $this->fooTypeMap);
  749. $result = $query->clause('where');
  750. $this->assertEquals($expected, $result);
  751. $this->assertEquals(1, $query->clause('limit'));
  752. $expected = new QueryExpression(['a > b']);
  753. $expected->typeMap($this->fooTypeMap);
  754. $result = $query->clause('join');
  755. $this->assertEquals([
  756. 'table_a' => ['alias' => 'table_a', 'type' => 'INNER', 'conditions' => $expected]
  757. ], $result);
  758. $expected = new OrderByExpression(['a' => 'ASC']);
  759. $this->assertEquals($expected, $query->clause('order'));
  760. $this->assertEquals(5, $query->clause('offset'));
  761. $this->assertEquals(['field_a'], $query->clause('group'));
  762. $expected = new QueryExpression($options['having']);
  763. $expected->typeMap($this->fooTypeMap);
  764. $this->assertEquals($expected, $query->clause('having'));
  765. $expected = ['table_a' => ['table_b' => []]];
  766. $this->assertEquals($expected, $query->contain());
  767. }
  768. /**
  769. * Test that page is applied after limit.
  770. *
  771. * @return void
  772. */
  773. public function testApplyOptionsPageIsLast() {
  774. $query = new Query($this->connection, $this->table);
  775. $opts = [
  776. 'page' => 3,
  777. 'limit' => 5
  778. ];
  779. $query->applyOptions($opts);
  780. $this->assertEquals(5, $query->clause('limit'));
  781. $this->assertEquals(10, $query->clause('offset'));
  782. }
  783. /**
  784. * ApplyOptions should ignore null values.
  785. *
  786. * @return void
  787. */
  788. public function testApplyOptionsIgnoreNull() {
  789. $options = [
  790. 'fields' => null,
  791. ];
  792. $query = new Query($this->connection, $this->table);
  793. $query->applyOptions($options);
  794. $this->assertEquals([], $query->clause('select'));
  795. }
  796. /**
  797. * Tests getOptions() method
  798. *
  799. * @return void
  800. */
  801. public function testGetOptions() {
  802. $options = ['doABarrelRoll' => true, 'fields' => ['id', 'name']];
  803. $query = new Query($this->connection, $this->table);
  804. $query->applyOptions($options);
  805. $expected = ['doABarrelRoll' => true];
  806. $this->assertEquals($expected, $query->getOptions());
  807. $expected = ['doABarrelRoll' => false, 'doAwesome' => true];
  808. $query->applyOptions($expected);
  809. $this->assertEquals($expected, $query->getOptions());
  810. }
  811. /**
  812. * Tests registering mappers with mapReduce()
  813. *
  814. * @return void
  815. */
  816. public function testMapReduceOnlyMapper() {
  817. $mapper1 = function () {
  818. };
  819. $mapper2 = function () {
  820. };
  821. $query = new Query($this->connection, $this->table);
  822. $this->assertSame($query, $query->mapReduce($mapper1));
  823. $this->assertEquals(
  824. [['mapper' => $mapper1, 'reducer' => null]],
  825. $query->mapReduce()
  826. );
  827. $this->assertEquals($query, $query->mapReduce($mapper2));
  828. $result = $query->mapReduce();
  829. $this->assertSame(
  830. [
  831. ['mapper' => $mapper1, 'reducer' => null],
  832. ['mapper' => $mapper2, 'reducer' => null]
  833. ],
  834. $result
  835. );
  836. }
  837. /**
  838. * Tests registering mappers and reducers with mapReduce()
  839. *
  840. * @return void
  841. */
  842. public function testMapReduceBothMethods() {
  843. $mapper1 = function () {
  844. };
  845. $mapper2 = function () {
  846. };
  847. $reducer1 = function () {
  848. };
  849. $reducer2 = function () {
  850. };
  851. $query = new Query($this->connection, $this->table);
  852. $this->assertSame($query, $query->mapReduce($mapper1, $reducer1));
  853. $this->assertEquals(
  854. [['mapper' => $mapper1, 'reducer' => $reducer1]],
  855. $query->mapReduce()
  856. );
  857. $this->assertSame($query, $query->mapReduce($mapper2, $reducer2));
  858. $this->assertEquals(
  859. [
  860. ['mapper' => $mapper1, 'reducer' => $reducer1],
  861. ['mapper' => $mapper2, 'reducer' => $reducer2]
  862. ],
  863. $query->mapReduce()
  864. );
  865. }
  866. /**
  867. * Tests that it is possible to overwrite previous map reducers
  868. *
  869. * @return void
  870. */
  871. public function testOverwriteMapReduce() {
  872. $mapper1 = function () {
  873. };
  874. $mapper2 = function () {
  875. };
  876. $reducer1 = function () {
  877. };
  878. $reducer2 = function () {
  879. };
  880. $query = new Query($this->connection, $this->table);
  881. $this->assertEquals($query, $query->mapReduce($mapper1, $reducer1));
  882. $this->assertEquals(
  883. [['mapper' => $mapper1, 'reducer' => $reducer1]],
  884. $query->mapReduce()
  885. );
  886. $this->assertEquals($query, $query->mapReduce($mapper2, $reducer2, true));
  887. $this->assertEquals(
  888. [['mapper' => $mapper2, 'reducer' => $reducer2]],
  889. $query->mapReduce()
  890. );
  891. }
  892. /**
  893. * Tests that multiple map reducers can be stacked
  894. *
  895. * @return void
  896. */
  897. public function testResultsAreWrappedInMapReduce() {
  898. $params = [$this->connection, $this->table];
  899. $query = $this->getMock('\Cake\ORM\Query', ['execute'], $params);
  900. $statement = $this->getMock(
  901. '\Database\StatementInterface',
  902. ['fetch', 'closeCursor', 'rowCount']
  903. );
  904. $statement->expects($this->exactly(3))
  905. ->method('fetch')
  906. ->will($this->onConsecutiveCalls(['a' => 1], ['a' => 2], false));
  907. $statement->expects($this->once())
  908. ->method('rowCount')
  909. ->will($this->returnValue(2));
  910. $query->expects($this->once())
  911. ->method('execute')
  912. ->will($this->returnValue($statement));
  913. $query->mapReduce(function ($v, $k, $mr) {
  914. $mr->emit($v['a']);
  915. });
  916. $query->mapReduce(
  917. function ($v, $k, $mr) {
  918. $mr->emitIntermediate($v, $k);
  919. },
  920. function ($v, $k, $mr) {
  921. $mr->emit($v[0] + 1);
  922. }
  923. );
  924. $this->assertEquals([2, 3], iterator_to_array($query->all()));
  925. }
  926. /**
  927. * Tests first() method when the query has not been executed before
  928. *
  929. * @return void
  930. */
  931. public function testFirstDirtyQuery() {
  932. $table = TableRegistry::get('articles', ['table' => 'articles']);
  933. $query = new Query($this->connection, $table);
  934. $result = $query->select(['id'])->hydrate(false)->first();
  935. $this->assertEquals(['id' => 1], $result);
  936. $this->assertEquals(1, $query->clause('limit'));
  937. $result = $query->select(['id'])->first();
  938. $this->assertEquals(['id' => 1], $result);
  939. }
  940. /**
  941. * Tests that first can be called again on an already executed query
  942. *
  943. * @return void
  944. */
  945. public function testFirstCleanQuery() {
  946. $table = TableRegistry::get('articles', ['table' => 'articles']);
  947. $query = new Query($this->connection, $table);
  948. $query->select(['id'])->toArray();
  949. $first = $query->hydrate(false)->first();
  950. $this->assertEquals(['id' => 1], $first);
  951. $this->assertEquals(1, $query->clause('limit'));
  952. }
  953. /**
  954. * Tests that first() will not execute the same query twice
  955. *
  956. * @return void
  957. */
  958. public function testFirstSameResult() {
  959. $table = TableRegistry::get('articles', ['table' => 'articles']);
  960. $query = new Query($this->connection, $table);
  961. $query->select(['id'])->toArray();
  962. $first = $query->hydrate(false)->first();
  963. $resultSet = $query->all();
  964. $this->assertEquals(['id' => 1], $first);
  965. $this->assertSame($resultSet, $query->all());
  966. }
  967. /**
  968. * Tests that first can be called against a query with a mapReduce
  969. *
  970. * @return void
  971. */
  972. public function testFirstMapReduce() {
  973. $map = function ($row, $key, $mapReduce) {
  974. $mapReduce->emitIntermediate($row['id'], 'id');
  975. };
  976. $reduce = function ($values, $key, $mapReduce) {
  977. $mapReduce->emit(array_sum($values));
  978. };
  979. $table = TableRegistry::get('articles', ['table' => 'articles']);
  980. $query = new Query($this->connection, $table);
  981. $query->select(['id'])
  982. ->hydrate(false)
  983. ->mapReduce($map, $reduce);
  984. $first = $query->first();
  985. $this->assertEquals(1, $first);
  986. }
  987. /**
  988. * Testing hydrating a result set into Entity objects
  989. *
  990. * @return void
  991. */
  992. public function testHydrateSimple() {
  993. $table = TableRegistry::get('articles', ['table' => 'articles']);
  994. $query = new Query($this->connection, $table);
  995. $results = $query->select()->toArray();
  996. $this->assertCount(3, $results);
  997. foreach ($results as $r) {
  998. $this->assertInstanceOf('\Cake\ORM\Entity', $r);
  999. }
  1000. $first = $results[0];
  1001. $this->assertEquals(1, $first->id);
  1002. $this->assertEquals(1, $first->author_id);
  1003. $this->assertEquals('First Article', $first->title);
  1004. $this->assertEquals('First Article Body', $first->body);
  1005. $this->assertEquals('Y', $first->published);
  1006. }
  1007. /**
  1008. * Tests that has many results are also hydrated correctly
  1009. *
  1010. * @return void
  1011. */
  1012. public function testHydrateHasMany() {
  1013. $table = TableRegistry::get('authors');
  1014. TableRegistry::get('articles');
  1015. $table->hasMany('articles', [
  1016. 'propertyName' => 'articles',
  1017. 'sort' => ['articles.id' => 'asc']
  1018. ]);
  1019. $query = new Query($this->connection, $table);
  1020. $results = $query->select()
  1021. ->contain('articles')
  1022. ->toArray();
  1023. $first = $results[0];
  1024. foreach ($first->articles as $r) {
  1025. $this->assertInstanceOf('\Cake\ORM\Entity', $r);
  1026. }
  1027. $this->assertCount(2, $first->articles);
  1028. $expected = [
  1029. 'id' => 1,
  1030. 'title' => 'First Article',
  1031. 'body' => 'First Article Body',
  1032. 'author_id' => 1,
  1033. 'published' => 'Y',
  1034. ];
  1035. $this->assertEquals($expected, $first->articles[0]->toArray());
  1036. $expected = [
  1037. 'id' => 3,
  1038. 'title' => 'Third Article',
  1039. 'author_id' => 1,
  1040. 'body' => 'Third Article Body',
  1041. 'published' => 'Y',
  1042. ];
  1043. $this->assertEquals($expected, $first->articles[1]->toArray());
  1044. }
  1045. /**
  1046. * Tests that belongsToMany associations are also correctly hydrated
  1047. *
  1048. * @return void
  1049. */
  1050. public function testHydrateBelongsToMany() {
  1051. $table = TableRegistry::get('Articles');
  1052. TableRegistry::get('Tags');
  1053. TableRegistry::get('ArticlesTags', [
  1054. 'table' => 'articles_tags'
  1055. ]);
  1056. $table->belongsToMany('Tags');
  1057. $query = new Query($this->connection, $table);
  1058. $results = $query
  1059. ->select()
  1060. ->contain('Tags')
  1061. ->toArray();
  1062. $first = $results[0];
  1063. foreach ($first->tags as $r) {
  1064. $this->assertInstanceOf('\Cake\ORM\Entity', $r);
  1065. }
  1066. $this->assertCount(2, $first->tags);
  1067. $expected = [
  1068. 'id' => 1,
  1069. 'name' => 'tag1',
  1070. '_joinData' => ['article_id' => 1, 'tag_id' => 1]
  1071. ];
  1072. $this->assertEquals($expected, $first->tags[0]->toArray());
  1073. $expected = [
  1074. 'id' => 2,
  1075. 'name' => 'tag2',
  1076. '_joinData' => ['article_id' => 1, 'tag_id' => 2]
  1077. ];
  1078. $this->assertEquals($expected, $first->tags[1]->toArray());
  1079. }
  1080. /**
  1081. * Tests that belongsTo relations are correctly hydrated
  1082. *
  1083. * @dataProvider internalStategiesProvider
  1084. * @return void
  1085. */
  1086. public function testHydrateBelongsTo($strategy) {
  1087. $table = TableRegistry::get('articles');
  1088. TableRegistry::get('authors');
  1089. $table->belongsTo('authors', ['strategy' => $strategy]);
  1090. $query = new Query($this->connection, $table);
  1091. $results = $query->select()
  1092. ->contain('authors')
  1093. ->order(['articles.id' => 'asc'])
  1094. ->toArray();
  1095. $this->assertCount(3, $results);
  1096. $first = $results[0];
  1097. $this->assertInstanceOf('\Cake\ORM\Entity', $first->author);
  1098. $expected = ['id' => 1, 'name' => 'mariano'];
  1099. $this->assertEquals($expected, $first->author->toArray());
  1100. }
  1101. /**
  1102. * Tests that deeply nested associations are also hydrated correctly
  1103. *
  1104. * @dataProvider internalStategiesProvider
  1105. * @return void
  1106. */
  1107. public function testHydrateDeep($strategy) {
  1108. $table = TableRegistry::get('authors');
  1109. $article = TableRegistry::get('articles');
  1110. $table->hasMany('articles', [
  1111. 'propertyName' => 'articles',
  1112. 'sort' => ['articles.id' => 'asc']
  1113. ]);
  1114. $article->belongsTo('authors', ['strategy' => $strategy]);
  1115. $query = new Query($this->connection, $table);
  1116. $results = $query->select()
  1117. ->contain(['articles' => ['authors']])
  1118. ->toArray();
  1119. $this->assertCount(4, $results);
  1120. $first = $results[0];
  1121. $this->assertInstanceOf('\Cake\ORM\Entity', $first->articles[0]->author);
  1122. $expected = ['id' => 1, 'name' => 'mariano'];
  1123. $this->assertEquals($expected, $first->articles[0]->author->toArray());
  1124. $this->assertTrue(isset($results[3]->articles));
  1125. }
  1126. /**
  1127. * Tests that it is possible to use a custom entity class
  1128. *
  1129. * @return void
  1130. */
  1131. public function testHydrateCustomObject() {
  1132. $class = $this->getMockClass('\Cake\ORM\Entity', ['fakeMethod']);
  1133. $table = TableRegistry::get('articles', [
  1134. 'table' => 'articles',
  1135. 'entityClass' => '\\' . $class
  1136. ]);
  1137. $query = new Query($this->connection, $table);
  1138. $results = $query->select()->toArray();
  1139. $this->assertCount(3, $results);
  1140. foreach ($results as $r) {
  1141. $this->assertInstanceOf($class, $r);
  1142. }
  1143. $first = $results[0];
  1144. $this->assertEquals(1, $first->id);
  1145. $this->assertEquals(1, $first->author_id);
  1146. $this->assertEquals('First Article', $first->title);
  1147. $this->assertEquals('First Article Body', $first->body);
  1148. $this->assertEquals('Y', $first->published);
  1149. }
  1150. /**
  1151. * Tests that has many results are also hydrated correctly
  1152. * when specified a custom entity class
  1153. *
  1154. * @return void
  1155. */
  1156. public function testHydrateHasManyCustomEntity() {
  1157. $authorEntity = $this->getMockClass('\Cake\ORM\Entity', ['foo']);
  1158. $articleEntity = $this->getMockClass('\Cake\ORM\Entity', ['foo']);
  1159. $table = TableRegistry::get('authors', [
  1160. 'entityClass' => '\\' . $authorEntity
  1161. ]);
  1162. TableRegistry::get('articles', [
  1163. 'entityClass' => '\\' . $articleEntity
  1164. ]);
  1165. $table->hasMany('articles', [
  1166. 'propertyName' => 'articles',
  1167. 'sort' => ['articles.id' => 'asc']
  1168. ]);
  1169. $query = new Query($this->connection, $table);
  1170. $results = $query->select()
  1171. ->contain('articles')
  1172. ->toArray();
  1173. $first = $results[0];
  1174. $this->assertInstanceOf($authorEntity, $first);
  1175. foreach ($first->articles as $r) {
  1176. $this->assertInstanceOf($articleEntity, $r);
  1177. }
  1178. $this->assertCount(2, $first->articles);
  1179. $expected = [
  1180. 'id' => 1,
  1181. 'title' => 'First Article',
  1182. 'body' => 'First Article Body',
  1183. 'author_id' => 1,
  1184. 'published' => 'Y',
  1185. ];
  1186. $this->assertEquals($expected, $first->articles[0]->toArray());
  1187. }
  1188. /**
  1189. * Tests that belongsTo relations are correctly hydrated into a custom entity class
  1190. *
  1191. * @return void
  1192. */
  1193. public function testHydrateBelongsToCustomEntity() {
  1194. $authorEntity = $this->getMockClass('\Cake\ORM\Entity', ['foo']);
  1195. $table = TableRegistry::get('articles');
  1196. TableRegistry::get('authors', [
  1197. 'entityClass' => '\\' . $authorEntity
  1198. ]);
  1199. $table->belongsTo('authors');
  1200. $query = new Query($this->connection, $table);
  1201. $results = $query->select()
  1202. ->contain('authors')
  1203. ->order(['articles.id' => 'asc'])
  1204. ->toArray();
  1205. $first = $results[0];
  1206. $this->assertInstanceOf($authorEntity, $first->author);
  1207. }
  1208. /**
  1209. * Test getting counts from queries.
  1210. *
  1211. * @return void
  1212. */
  1213. public function testCount() {
  1214. $table = TableRegistry::get('articles');
  1215. $result = $table->find('all')->count();
  1216. $this->assertSame(3, $result);
  1217. $query = $table->find('all')
  1218. ->where(['id >' => 1])
  1219. ->limit(1);
  1220. $result = $query->count();
  1221. $this->assertSame(2, $result);
  1222. $result = $query->all();
  1223. $this->assertCount(1, $result);
  1224. $this->assertEquals(2, $result->first()->id);
  1225. }
  1226. /**
  1227. * Test that count() returns correct results with group by.
  1228. *
  1229. * @return void
  1230. */
  1231. public function testCountWithGroup() {
  1232. $table = TableRegistry::get('articles');
  1233. $query = $table->find('all');
  1234. $query->select(['author_id', 's' => $query->func()->sum('id')])
  1235. ->group(['author_id']);
  1236. $result = $query->count();
  1237. $this->assertEquals(2, $result);
  1238. }
  1239. /**
  1240. * Tests that it is possible to provide a callback for calculating the count
  1241. * of a query
  1242. *
  1243. * @return void
  1244. */
  1245. public function testCountWithCustomCounter() {
  1246. $table = TableRegistry::get('articles');
  1247. $query = $table->find('all');
  1248. $query
  1249. ->select(['author_id', 's' => $query->func()->sum('id')])
  1250. ->where(['id >' => 2])
  1251. ->group(['author_id'])
  1252. ->counter(function ($q) use ($query) {
  1253. $this->assertNotSame($q, $query);
  1254. return $q->select([], true)->group([], true)->count();
  1255. });
  1256. $result = $query->count();
  1257. $this->assertEquals(1, $result);
  1258. }
  1259. /**
  1260. * Test update method.
  1261. *
  1262. * @return void
  1263. */
  1264. public function testUpdate() {
  1265. $table = TableRegistry::get('articles');
  1266. $result = $table->query()
  1267. ->update()
  1268. ->set(['title' => 'First'])
  1269. ->execute();
  1270. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  1271. $this->assertTrue($result->rowCount() > 0);
  1272. }
  1273. /**
  1274. * Test insert method.
  1275. *
  1276. * @return void
  1277. */
  1278. public function testInsert() {
  1279. $table = TableRegistry::get('articles');
  1280. $result = $table->query()
  1281. ->insert(['title'])
  1282. ->values(['title' => 'First'])
  1283. ->values(['title' => 'Second'])
  1284. ->execute();
  1285. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  1286. $this->assertEquals(2, $result->rowCount());
  1287. }
  1288. /**
  1289. * Test delete method.
  1290. *
  1291. * @return void
  1292. */
  1293. public function testDelete() {
  1294. $table = TableRegistry::get('articles');
  1295. $result = $table->query()
  1296. ->delete()
  1297. ->where(['id >=' => 1])
  1298. ->execute();
  1299. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  1300. $this->assertTrue($result->rowCount() > 0);
  1301. }
  1302. /**
  1303. * Provides a list of collection methods that can be proxied
  1304. * from the query
  1305. *
  1306. * @return array
  1307. */
  1308. public function collectionMethodsProvider() {
  1309. $identity = function ($a) {
  1310. return $a;
  1311. };
  1312. return [
  1313. ['filter', $identity],
  1314. ['reject', $identity],
  1315. ['every', $identity],
  1316. ['some', $identity],
  1317. ['contains', $identity],
  1318. ['map', $identity],
  1319. ['reduce', $identity],
  1320. ['extract', $identity],
  1321. ['max', $identity],
  1322. ['min', $identity],
  1323. ['sortBy', $identity],
  1324. ['groupBy', $identity],
  1325. ['countBy', $identity],
  1326. ['shuffle', $identity],
  1327. ['sample', $identity],
  1328. ['take', 1],
  1329. ['append', new \ArrayIterator],
  1330. ['compile', 1],
  1331. ];
  1332. }
  1333. /**
  1334. * Tests that query can proxy collection methods
  1335. *
  1336. * @dataProvider collectionMethodsProvider
  1337. * @return void
  1338. */
  1339. public function testCollectionProxy($method, $arg) {
  1340. $query = $this->getMock(
  1341. '\Cake\ORM\Query', ['all'],
  1342. [$this->connection, $this->table]
  1343. );
  1344. $query->select();
  1345. $resultSet = $this->getMock('\Cake\ORM\ResultSet', [], [$query, null]);
  1346. $query->expects($this->once())
  1347. ->method('all')
  1348. ->will($this->returnValue($resultSet));
  1349. $resultSet->expects($this->once())
  1350. ->method($method)
  1351. ->with($arg, 'extra')
  1352. ->will($this->returnValue(new \Cake\Collection\Collection([])));
  1353. $this->assertInstanceOf(
  1354. '\Cake\Collection\Collection',
  1355. $query->{$method}($arg, 'extra')
  1356. );
  1357. }
  1358. /**
  1359. * Tests that calling an inexistent method in query throws an
  1360. * exception
  1361. *
  1362. * @expectedException \BadMethodCallException
  1363. * @expectedExceptionMessage Unknown method "derpFilter"
  1364. * @return void
  1365. */
  1366. public function testCollectionProxyBadMethod() {
  1367. TableRegistry::get('articles')->find('all')->derpFilter();
  1368. }
  1369. /**
  1370. * cache() should fail on non select queries.
  1371. *
  1372. * @expectedException RuntimeException
  1373. * @return void
  1374. */
  1375. public function testCacheErrorOnNonSelect() {
  1376. $table = TableRegistry::get('articles', ['table' => 'articles']);
  1377. $query = new Query($this->connection, $table);
  1378. $query->insert(['test']);
  1379. $query->cache('my_key');
  1380. }
  1381. /**
  1382. * Integration test for query caching.
  1383. *
  1384. * @return void
  1385. */
  1386. public function testCacheReadIntegration() {
  1387. $query = $this->getMock(
  1388. '\Cake\ORM\Query', ['execute'],
  1389. [$this->connection, $this->table]
  1390. );
  1391. $resultSet = $this->getMock('\Cake\ORM\ResultSet', [], [$query, null]);
  1392. $query->expects($this->never())
  1393. ->method('execute');
  1394. $cacher = $this->getMock('Cake\Cache\CacheEngine');
  1395. $cacher->expects($this->once())
  1396. ->method('read')
  1397. ->with('my_key')
  1398. ->will($this->returnValue($resultSet));
  1399. $query->cache('my_key', $cacher)
  1400. ->where(['id' => 1]);
  1401. $results = $query->all();
  1402. $this->assertSame($resultSet, $results);
  1403. }
  1404. /**
  1405. * Integration test for query caching.
  1406. *
  1407. * @return void
  1408. */
  1409. public function testCacheWriteIntegration() {
  1410. $table = TableRegistry::get('Articles');
  1411. $query = new Query($this->connection, $table);
  1412. $query->select(['id', 'title']);
  1413. $cacher = $this->getMock('Cake\Cache\CacheEngine');
  1414. $cacher->expects($this->once())
  1415. ->method('write')
  1416. ->with(
  1417. 'my_key',
  1418. $this->isInstanceOf('Cake\Datasource\ResultSetInterface')
  1419. );
  1420. $query->cache('my_key', $cacher)
  1421. ->where(['id' => 1]);
  1422. $query->all();
  1423. }
  1424. /**
  1425. * Integration test to show filtering associations using contain and a closure
  1426. *
  1427. * @return void
  1428. */
  1429. public function testContainWithClosure() {
  1430. $table = TableRegistry::get('authors');
  1431. $table->hasMany('articles');
  1432. $query = new Query($this->connection, $table);
  1433. $query
  1434. ->select()
  1435. ->contain(['articles' => function ($q) {
  1436. return $q->where(['articles.id' => 1]);
  1437. }]);
  1438. $ids = [];
  1439. foreach ($query as $entity) {
  1440. foreach ((array)$entity->articles as $article) {
  1441. $ids[] = $article->id;
  1442. }
  1443. }
  1444. $this->assertEquals([1], array_unique($ids));
  1445. }
  1446. /**
  1447. * Tests the formatResults method
  1448. *
  1449. * @return void
  1450. */
  1451. public function testFormatResults() {
  1452. $callback1 = function () {
  1453. };
  1454. $callback2 = function () {
  1455. };
  1456. $table = TableRegistry::get('authors');
  1457. $query = new Query($this->connection, $table);
  1458. $this->assertSame($query, $query->formatResults($callback1));
  1459. $this->assertSame([$callback1], $query->formatResults());
  1460. $this->assertSame($query, $query->formatResults($callback2));
  1461. $this->assertSame([$callback1, $callback2], $query->formatResults());
  1462. $query->formatResults($callback2, true);
  1463. $this->assertSame([$callback2], $query->formatResults());
  1464. $query->formatResults(null, true);
  1465. $this->assertSame([], $query->formatResults());
  1466. $query->formatResults($callback1);
  1467. $query->formatResults($callback2, $query::PREPEND);
  1468. $this->assertSame([$callback2, $callback1], $query->formatResults());
  1469. }
  1470. /**
  1471. * Test fetching results from a qurey with a custom formatter
  1472. *
  1473. * @return void
  1474. */
  1475. public function testQueryWithFormatter() {
  1476. $table = TableRegistry::get('authors');
  1477. $query = new Query($this->connection, $table);
  1478. $query->select()->formatResults(function ($results, $q) use ($query) {
  1479. $this->assertSame($query, $q);
  1480. $this->assertInstanceOf('\Cake\ORM\ResultSet', $results);
  1481. return $results->indexBy('id');
  1482. });
  1483. $this->assertEquals([1, 2, 3, 4], array_keys($query->toArray()));
  1484. }
  1485. /**
  1486. * Test fetching results from a qurey with a two custom formatters
  1487. *
  1488. * @return void
  1489. */
  1490. public function testQueryWithStackedFormatters() {
  1491. $table = TableRegistry::get('authors');
  1492. $query = new Query($this->connection, $table);
  1493. $query->select()->formatResults(function ($results, $q) use ($query) {
  1494. $this->assertSame($query, $q);
  1495. $this->assertInstanceOf('\Cake\ORM\ResultSet', $results);
  1496. return $results->indexBy('id');
  1497. });
  1498. $query->formatResults(function ($results) {
  1499. return $results->extract('name');
  1500. });
  1501. $expected = [
  1502. 1 => 'mariano',
  1503. 2 => 'nate',
  1504. 3 => 'larry',
  1505. 4 => 'garrett'
  1506. ];
  1507. $this->assertEquals($expected, $query->toArray());
  1508. }
  1509. /**
  1510. * Tests that getting results from a query having a contained association
  1511. * will no attach joins twice if count() is called on it afterwards
  1512. *
  1513. * @return void
  1514. */
  1515. public function testCountWithContainCallingAll() {
  1516. $table = TableRegistry::get('articles');
  1517. $table->belongsTo('authors');
  1518. $query = $table->find()
  1519. ->select(['id', 'title'])
  1520. ->contain('authors')
  1521. ->limit(2);
  1522. $results = $query->all();
  1523. $this->assertCount(2, $results);
  1524. $this->assertEquals(3, $query->count());
  1525. }
  1526. /**
  1527. * Tests that it is possible to apply formatters inside the query builder
  1528. * for belongsTo associations
  1529. *
  1530. * @return void
  1531. */
  1532. public function testFormatBelongsToRecords() {
  1533. $table = TableRegistry::get('articles');
  1534. $table->belongsTo('authors');
  1535. $query = $table->find()
  1536. ->contain(['authors' => function ($q) {
  1537. return $q
  1538. ->formatResults(function ($authors) {
  1539. return $authors->map(function ($author) {
  1540. $author->idCopy = $author->id;
  1541. return $author;
  1542. });
  1543. })
  1544. ->formatResults(function ($authors) {
  1545. return $authors->map(function ($author) {
  1546. $author->idCopy = $author->idCopy + 2;
  1547. return $author;
  1548. });
  1549. });
  1550. }]);
  1551. $query->formatResults(function ($results) {
  1552. return $results->combine('id', 'author.idCopy');
  1553. });
  1554. $results = $query->toArray();
  1555. $expected = [1 => 3, 2 => 5, 3 => 3];
  1556. $this->assertEquals($expected, $results);
  1557. }
  1558. /**
  1559. * Tests it is possible to apply formatters to deep relations.
  1560. *
  1561. * @return void
  1562. */
  1563. public function testFormatDeepAssocationRecords() {
  1564. $table = TableRegistry::get('ArticlesTags');
  1565. $table->belongsTo('Articles');
  1566. $table->association('Articles')->target()->belongsTo('Authors');
  1567. $builder = function ($q) {
  1568. return $q
  1569. ->formatResults(function ($results) {
  1570. return $results->map(function ($result) {
  1571. $result->idCopy = $result->id;
  1572. return $result;
  1573. });
  1574. })
  1575. ->formatResults(function ($results) {
  1576. return $results->map(function ($result) {
  1577. $result->idCopy = $result->idCopy + 2;
  1578. return $result;
  1579. });
  1580. });
  1581. };
  1582. $query = $table->find()
  1583. ->contain(['Articles' => $builder, 'Articles.Authors' => $builder])
  1584. ->order(['Articles.id' => 'ASC']);
  1585. $query->formatResults(function ($results) {
  1586. return $results->map(function ($row) {
  1587. return sprintf(
  1588. '%s - %s - %s',
  1589. $row->tag_id,
  1590. $row->article->idCopy,
  1591. $row->article->author->idCopy
  1592. );
  1593. });
  1594. });
  1595. $expected = ['1 - 3 - 3', '2 - 3 - 3', '1 - 4 - 5', '3 - 4 - 5'];
  1596. $this->assertEquals($expected, $query->toArray());
  1597. }
  1598. /**
  1599. * Tests that formatters cna be applied to deep associations that are fetched using
  1600. * additional queries
  1601. *
  1602. * @return void
  1603. */
  1604. public function testFormatDeepDistantAssociationRecords() {
  1605. $table = TableRegistry::get('authors');
  1606. $table->hasMany('articles');
  1607. $articles = $table->association('articles')->target();
  1608. $articles->hasMany('articlesTags');
  1609. $articles->association('articlesTags')->target()->belongsTo('tags');
  1610. $query = $table->find()->contain(['articles.articlesTags.tags' => function ($q) {
  1611. return $q->formatResults(function ($results) {
  1612. return $results->map(function ($tag) {
  1613. $tag->name .= ' - visited';
  1614. return $tag;
  1615. });
  1616. });
  1617. }]);
  1618. $query->mapReduce(function ($row, $key, $mr) {
  1619. foreach ((array)$row->articles as $article) {
  1620. foreach ((array)$article->articles_tags as $articleTag) {
  1621. $mr->emit($articleTag->tag->name);
  1622. }
  1623. }
  1624. });
  1625. $expected = ['tag1 - visited', 'tag2 - visited', 'tag1 - visited', 'tag3 - visited'];
  1626. $this->assertEquals($expected, $query->toArray());
  1627. }
  1628. /**
  1629. * Tests that custom finders are applied to associations when using the proxies
  1630. *
  1631. * @return void
  1632. */
  1633. public function testCustomFinderInBelongsTo() {
  1634. $table = TableRegistry::get('ArticlesTags');
  1635. $table->belongsTo('Articles', [
  1636. 'className' => 'TestApp\Model\Table\ArticlesTable',
  1637. 'finder' => 'published'
  1638. ]);
  1639. $result = $table->find()->contain('Articles');
  1640. $this->assertCount(4, $result->extract('article')->filter()->toArray());
  1641. $table->Articles->updateAll(['published' => 'N'], ['1 = 1']);
  1642. $result = $table->find()->contain('Articles');
  1643. $this->assertCount(0, $result->extract('article')->filter()->toArray());
  1644. }
  1645. /**
  1646. * Tests that it is possible to attach more association when using a query
  1647. * builder for other associations
  1648. *
  1649. * @return void
  1650. */
  1651. public function testContainInAssociationQuery() {
  1652. $table = TableRegistry::get('ArticlesTags');
  1653. $table->belongsTo('Articles');
  1654. $table->association('Articles')->target()->belongsTo('Authors');
  1655. $query = $table->find()
  1656. ->order(['Articles.id' => 'ASC'])
  1657. ->contain(['Articles' => function ($q) {
  1658. return $q->contain('Authors');
  1659. }]);
  1660. $results = $query->extract('article.author.name')->toArray();
  1661. $expected = ['mariano', 'mariano', 'larry', 'larry'];
  1662. $this->assertEquals($expected, $results);
  1663. }
  1664. /**
  1665. * Tests that it is possible to apply more `matching` conditions inside query
  1666. * builders for associations
  1667. *
  1668. * @return void
  1669. */
  1670. public function testContainInAssociationMatching() {
  1671. $table = TableRegistry::get('authors');
  1672. $table->hasMany('articles');
  1673. $articles = $table->association('articles')->target();
  1674. $articles->hasMany('articlesTags');
  1675. $articles->association('articlesTags')->target()->belongsTo('tags');
  1676. $query = $table->find()->matching('articles.articlesTags', function ($q) {
  1677. return $q->matching('tags', function ($q) {
  1678. return $q->where(['tags.name' => 'tag3']);
  1679. });
  1680. });
  1681. $results = $query->toArray();
  1682. $this->assertCount(1, $results);
  1683. $this->assertEquals('tag3', $results[0]->articles->articles_tags->tag->name);
  1684. }
  1685. /**
  1686. * Tests __debugInfo
  1687. *
  1688. * @return void
  1689. */
  1690. public function testDebugInfo() {
  1691. $table = TableRegistry::get('authors');
  1692. $table->hasMany('articles');
  1693. $query = $table->find()
  1694. ->where(['id > ' => 1])
  1695. ->bufferResults(false)
  1696. ->hydrate(false)
  1697. ->matching('articles')
  1698. ->applyOptions(['foo' => 'bar'])
  1699. ->formatResults(function ($results) {
  1700. return $results;
  1701. })
  1702. ->mapReduce(function ($item, $key, $mr) {
  1703. $mr->emit($item);
  1704. });
  1705. $expected = [
  1706. 'sql' => $query->sql(),
  1707. 'params' => $query->valueBinder()->bindings(),
  1708. 'defaultTypes' => [
  1709. 'authors.id' => 'integer',
  1710. 'id' => 'integer',
  1711. 'authors.name' => 'string',
  1712. 'name' => 'string'
  1713. ],
  1714. 'decorators' => 0,
  1715. 'executed' => false,
  1716. 'hydrate' => false,
  1717. 'buffered' => false,
  1718. 'formatters' => 1,
  1719. 'mapReducers' => 1,
  1720. 'contain' => [
  1721. 'articles' => [
  1722. 'queryBuilder' => null,
  1723. 'matching' => true
  1724. ]
  1725. ],
  1726. 'extraOptions' => ['foo' => 'bar'],
  1727. 'repository' => $table
  1728. ];
  1729. $this->assertSame($expected, $query->__debugInfo());
  1730. }
  1731. /**
  1732. * Tests that the eagerLoaded function works and is transmitted correctly to eagerly
  1733. * loaded associations
  1734. *
  1735. * @return void
  1736. */
  1737. public function testEagerLoaded() {
  1738. $table = TableRegistry::get('authors');
  1739. $table->hasMany('articles');
  1740. $query = $table->find()->contain(['articles' => function ($q) {
  1741. $this->assertTrue($q->eagerLoaded());
  1742. return $q;
  1743. }]);
  1744. $this->assertFalse($query->eagerLoaded());
  1745. $table->eventManager()->attach(function ($e, $q, $o, $primary) {
  1746. $this->assertTrue($primary);
  1747. }, 'Model.beforeFind');
  1748. TableRegistry::get('articles')
  1749. ->eventManager()->attach(function ($e, $q, $o, $primary) {
  1750. $this->assertFalse($primary);
  1751. }, 'Model.beforeFind');
  1752. $query->all();
  1753. }
  1754. /**
  1755. * Tests that columns from manual joins are also contained in the result set
  1756. *
  1757. * @return void
  1758. */
  1759. public function testColumnsFromJoin() {
  1760. $table = TableRegistry::get('articles');
  1761. $results = $table->find()
  1762. ->select(['title', 'person.name'])
  1763. ->join([
  1764. 'person' => [
  1765. 'table' => 'authors',
  1766. 'conditions' => ['person.id = articles.author_id']
  1767. ]
  1768. ])
  1769. ->order(['articles.id' => 'ASC'])
  1770. ->hydrate(false)
  1771. ->toArray();
  1772. $expected = [
  1773. ['title' => 'First Article', 'person' => ['name' => 'mariano']],
  1774. ['title' => 'Second Article', 'person' => ['name' => 'larry']],
  1775. ['title' => 'Third Article', 'person' => ['name' => 'mariano']],
  1776. ];
  1777. $this->assertSame($expected, $results);
  1778. }
  1779. /**
  1780. * Tests that it is possible to use the same association aliases in the association
  1781. * chain for contain
  1782. *
  1783. * @dataProvider internalStategiesProvider
  1784. * @return void
  1785. */
  1786. public function testRepeatedAssociationAliases($strategy) {
  1787. $table = TableRegistry::get('ArticlesTags');
  1788. $table->belongsTo('Articles', ['strategy' => $strategy]);
  1789. $table->belongsTo('Tags', ['strategy' => $strategy]);
  1790. TableRegistry::get('Tags')->belongsToMany('Articles');
  1791. $results = $table
  1792. ->find()
  1793. ->contain(['Articles', 'Tags.Articles'])
  1794. ->hydrate(false)
  1795. ->toArray();
  1796. $this->assertNotEmpty($results[0]['tag']['articles']);
  1797. $this->assertNotEmpty($results[0]['article']);
  1798. $this->assertNotEmpty($results[1]['tag']['articles']);
  1799. $this->assertNotEmpty($results[1]['article']);
  1800. $this->assertNotEmpty($results[2]['tag']['articles']);
  1801. $this->assertNotEmpty($results[2]['article']);
  1802. }
  1803. /**
  1804. * Tests that it is not allowed to use matching on an association
  1805. * that is already added to containments.
  1806. *
  1807. * @expectedException RuntimeException
  1808. * @expectedExceptionMessage Cannot use "matching" on "Authors" as there is another association with the same alias
  1809. * @return void
  1810. */
  1811. public function testConflitingAliases() {
  1812. $table = TableRegistry::get('ArticlesTags');
  1813. $table->belongsTo('Articles')->target()->belongsTo('Authors');
  1814. $table->belongsTo('Tags');
  1815. $table->Tags->target()->hasOne('Authors');
  1816. $table->find()
  1817. ->contain(['Articles.Authors'])
  1818. ->matching('Tags.Authors')
  1819. ->all();
  1820. }
  1821. /**
  1822. * Tests that a hasOne association using the select strategy will still have the
  1823. * key present in the results when no match is found
  1824. *
  1825. * @return void
  1826. */
  1827. public function testAssociationKeyPresent() {
  1828. $table = TableRegistry::get('Articles');
  1829. $table->hasOne('ArticlesTags', ['strategy' => 'select']);
  1830. $article = $table->find()->where(['id' => 3])
  1831. ->hydrate(false)
  1832. ->contain('ArticlesTags')
  1833. ->first();
  1834. $this->assertNull($article['articles_tag']);
  1835. }
  1836. /**
  1837. * Tests that queries can be serialized to JSON to get the results
  1838. *
  1839. * @return void
  1840. */
  1841. public function testJsonSerialize() {
  1842. $table = TableRegistry::get('Articles');
  1843. $this->assertEquals(
  1844. json_encode($table->find()),
  1845. json_encode($table->find()->toArray())
  1846. );
  1847. }
  1848. /**
  1849. * Test that addFields() works in the basic case.
  1850. *
  1851. * @return void
  1852. */
  1853. public function testAutoFields() {
  1854. $table = TableRegistry::get('Articles');
  1855. $result = $table->find('all')
  1856. ->select(['myField' => '(SELECT 20)'])
  1857. ->autoFields(true)
  1858. ->hydrate(false)
  1859. ->first();
  1860. $this->assertArrayHasKey('myField', $result);
  1861. $this->assertArrayHasKey('id', $result);
  1862. $this->assertArrayHasKey('title', $result);
  1863. }
  1864. /**
  1865. * Test autoFields with auto fields.
  1866. *
  1867. * @return void
  1868. */
  1869. public function testAutoFieldsWithAssociations() {
  1870. $table = TableRegistry::get('Articles');
  1871. $table->belongsTo('Authors');
  1872. $result = $table->find()
  1873. ->select(['myField' => '(SELECT 2 + 2)'])
  1874. ->autoFields(true)
  1875. ->hydrate(false)
  1876. ->contain('Authors')
  1877. ->first();
  1878. $this->assertArrayHasKey('myField', $result);
  1879. $this->assertArrayHasKey('title', $result);
  1880. $this->assertArrayHasKey('author', $result);
  1881. $this->assertNotNull($result['author']);
  1882. $this->assertArrayHasKey('name', $result['author']);
  1883. }
  1884. /**
  1885. * Test autoFields in contain query builder
  1886. *
  1887. * @return void
  1888. */
  1889. public function testAutoFieldsWithContainQueryBuilder() {
  1890. $table = TableRegistry::get('Articles');
  1891. $table->belongsTo('Authors');
  1892. $result = $table->find()
  1893. ->select(['myField' => '(SELECT 2 + 2)'])
  1894. ->autoFields(true)
  1895. ->hydrate(false)
  1896. ->contain(['Authors' => function ($q) {
  1897. return $q->select(['compute' => '(SELECT 2 + 20)'])
  1898. ->autoFields(true);
  1899. }])
  1900. ->first();
  1901. $this->assertArrayHasKey('myField', $result);
  1902. $this->assertArrayHasKey('title', $result);
  1903. $this->assertArrayHasKey('author', $result);
  1904. $this->assertNotNull($result['author']);
  1905. $this->assertArrayHasKey('name', $result['author']);
  1906. $this->assertArrayHasKey('compute', $result);
  1907. }
  1908. /**
  1909. * Test that autofields works with count()
  1910. *
  1911. * @return void
  1912. */
  1913. public function testAutoFieldsCount() {
  1914. $table = TableRegistry::get('Articles');
  1915. $result = $table->find()
  1916. ->select(['myField' => '(SELECT (2 + 2))'])
  1917. ->autoFields(true)
  1918. ->count();
  1919. $this->assertEquals(3, $result);
  1920. }
  1921. /**
  1922. * test that cleanCopy makes a cleaned up clone.
  1923. *
  1924. * @return void
  1925. */
  1926. public function testCleanCopy() {
  1927. $table = TableRegistry::get('Articles');
  1928. $table->hasMany('Comments');
  1929. $query = $table->find();
  1930. $query->offset(10)
  1931. ->limit(1)
  1932. ->order(['Articles.id' => 'DESC'])
  1933. ->contain(['Comments']);
  1934. $copy = $query->cleanCopy();
  1935. $this->assertNotSame($copy, $query);
  1936. $this->assertNull($copy->clause('offset'));
  1937. $this->assertNull($copy->clause('limit'));
  1938. $this->assertNull($copy->clause('order'));
  1939. }
  1940. /**
  1941. * Test that finder options sent through via contain are sent to custom finder.
  1942. *
  1943. * @return void
  1944. */
  1945. public function testContainFinderCanSpecifyOptions() {
  1946. $table = TableRegistry::get('Articles');
  1947. $table->belongsTo(
  1948. 'Authors',
  1949. ['className' => 'TestApp\Model\Table\AuthorsTable']
  1950. );
  1951. $authorId = 1;
  1952. $resultWithoutAuthor = $table->find('all')
  1953. ->where(['Articles.author_id' => $authorId])
  1954. ->contain([
  1955. 'Authors' => [
  1956. 'finder' => ['byAuthor' => ['author_id' => 2]]
  1957. ]
  1958. ]);
  1959. $resultWithAuthor = $table->find('all')
  1960. ->where(['Articles.author_id' => $authorId])
  1961. ->contain([
  1962. 'Authors' => [
  1963. 'finder' => ['byAuthor' => ['author_id' => $authorId]]
  1964. ]
  1965. ]);
  1966. $this->assertEmpty($resultWithoutAuthor->first()['author']);
  1967. $this->assertEquals($authorId, $resultWithAuthor->first()['author']['id']);
  1968. }
  1969. /**
  1970. * Tests that it is possible to pass a custom join type for an association when
  1971. * using contain
  1972. *
  1973. * @return void
  1974. */
  1975. public function testContainWithCustomJoinType() {
  1976. $table = TableRegistry::get('Articles');
  1977. $table->belongsTo('Authors');
  1978. $articles = $table->find()
  1979. ->contain([
  1980. 'Authors' => [
  1981. 'joinType' => 'inner',
  1982. 'conditions' => ['Authors.id' => 3]
  1983. ]
  1984. ])
  1985. ->toArray();
  1986. $this->assertCount(1, $articles);
  1987. $this->assertEquals(3, $articles[0]->author->id);
  1988. }
  1989. }