QueryTest.php 74 KB

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