QueryTest.php 78 KB

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