QueryTest.php 81 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645
  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 update method.
  1420. *
  1421. * @return void
  1422. */
  1423. public function testUpdateWithTableExpression()
  1424. {
  1425. $this->skipIf(!$this->connection->driver() instanceof \Cake\Database\Driver\Mysql);
  1426. $table = TableRegistry::get('articles');
  1427. $query = $table->query();
  1428. $result = $query->update($query->newExpr('articles, authors'))
  1429. ->set(['title' => 'First'])
  1430. ->where(['articles.author_id = authors.id'])
  1431. ->andWhere(['authors.name' => 'mariano'])
  1432. ->execute();
  1433. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  1434. $this->assertTrue($result->rowCount() > 0);
  1435. }
  1436. /**
  1437. * Test insert method.
  1438. *
  1439. * @return void
  1440. */
  1441. public function testInsert()
  1442. {
  1443. $table = TableRegistry::get('articles');
  1444. $result = $table->query()
  1445. ->insert(['title'])
  1446. ->values(['title' => 'First'])
  1447. ->values(['title' => 'Second'])
  1448. ->execute();
  1449. $result->closeCursor();
  1450. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  1451. //PDO_SQLSRV returns -1 for successful inserts when using INSERT ... OUTPUT
  1452. if (!$this->connection->driver() instanceof \Cake\Database\Driver\Sqlserver) {
  1453. $this->assertEquals(2, $result->rowCount());
  1454. } else {
  1455. $this->assertEquals(-1, $result->rowCount());
  1456. }
  1457. }
  1458. /**
  1459. * Test delete method.
  1460. *
  1461. * @return void
  1462. */
  1463. public function testDelete()
  1464. {
  1465. $table = TableRegistry::get('articles');
  1466. $result = $table->query()
  1467. ->delete()
  1468. ->where(['id >=' => 1])
  1469. ->execute();
  1470. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  1471. $this->assertTrue($result->rowCount() > 0);
  1472. }
  1473. /**
  1474. * Provides a list of collection methods that can be proxied
  1475. * from the query
  1476. *
  1477. * @return array
  1478. */
  1479. public function collectionMethodsProvider()
  1480. {
  1481. $identity = function ($a) {
  1482. return $a;
  1483. };
  1484. return [
  1485. ['filter', $identity],
  1486. ['reject', $identity],
  1487. ['every', $identity],
  1488. ['some', $identity],
  1489. ['contains', $identity],
  1490. ['map', $identity],
  1491. ['reduce', $identity],
  1492. ['extract', $identity],
  1493. ['max', $identity],
  1494. ['min', $identity],
  1495. ['sortBy', $identity],
  1496. ['groupBy', $identity],
  1497. ['countBy', $identity],
  1498. ['shuffle', $identity],
  1499. ['sample', $identity],
  1500. ['take', 1],
  1501. ['append', new \ArrayIterator],
  1502. ['compile', 1],
  1503. ];
  1504. }
  1505. /**
  1506. * Tests that query can proxy collection methods
  1507. *
  1508. * @dataProvider collectionMethodsProvider
  1509. * @return void
  1510. */
  1511. public function testCollectionProxy($method, $arg)
  1512. {
  1513. $query = $this->getMock(
  1514. '\Cake\ORM\Query',
  1515. ['all'],
  1516. [$this->connection, $this->table]
  1517. );
  1518. $query->select();
  1519. $resultSet = $this->getMock('\Cake\ORM\ResultSet', [], [$query, null]);
  1520. $query->expects($this->once())
  1521. ->method('all')
  1522. ->will($this->returnValue($resultSet));
  1523. $resultSet->expects($this->once())
  1524. ->method($method)
  1525. ->with($arg, 'extra')
  1526. ->will($this->returnValue(new \Cake\Collection\Collection([])));
  1527. $this->assertInstanceOf(
  1528. '\Cake\Collection\Collection',
  1529. $query->{$method}($arg, 'extra')
  1530. );
  1531. }
  1532. /**
  1533. * Tests that calling an inexistent method in query throws an
  1534. * exception
  1535. *
  1536. * @expectedException \BadMethodCallException
  1537. * @expectedExceptionMessage Unknown method "derpFilter"
  1538. * @return void
  1539. */
  1540. public function testCollectionProxyBadMethod()
  1541. {
  1542. TableRegistry::get('articles')->find('all')->derpFilter();
  1543. }
  1544. /**
  1545. * cache() should fail on non select queries.
  1546. *
  1547. * @expectedException \RuntimeException
  1548. * @return void
  1549. */
  1550. public function testCacheErrorOnNonSelect()
  1551. {
  1552. $table = TableRegistry::get('articles', ['table' => 'articles']);
  1553. $query = new Query($this->connection, $table);
  1554. $query->insert(['test']);
  1555. $query->cache('my_key');
  1556. }
  1557. /**
  1558. * Integration test for query caching.
  1559. *
  1560. * @return void
  1561. */
  1562. public function testCacheReadIntegration()
  1563. {
  1564. $query = $this->getMock(
  1565. '\Cake\ORM\Query',
  1566. ['execute'],
  1567. [$this->connection, $this->table]
  1568. );
  1569. $resultSet = $this->getMock('\Cake\ORM\ResultSet', [], [$query, null]);
  1570. $query->expects($this->never())
  1571. ->method('execute');
  1572. $cacher = $this->getMock('Cake\Cache\CacheEngine');
  1573. $cacher->expects($this->once())
  1574. ->method('read')
  1575. ->with('my_key')
  1576. ->will($this->returnValue($resultSet));
  1577. $query->cache('my_key', $cacher)
  1578. ->where(['id' => 1]);
  1579. $results = $query->all();
  1580. $this->assertSame($resultSet, $results);
  1581. }
  1582. /**
  1583. * Integration test for query caching.
  1584. *
  1585. * @return void
  1586. */
  1587. public function testCacheWriteIntegration()
  1588. {
  1589. $table = TableRegistry::get('Articles');
  1590. $query = new Query($this->connection, $table);
  1591. $query->select(['id', 'title']);
  1592. $cacher = $this->getMock('Cake\Cache\CacheEngine');
  1593. $cacher->expects($this->once())
  1594. ->method('write')
  1595. ->with(
  1596. 'my_key',
  1597. $this->isInstanceOf('Cake\Datasource\ResultSetInterface')
  1598. );
  1599. $query->cache('my_key', $cacher)
  1600. ->where(['id' => 1]);
  1601. $query->all();
  1602. }
  1603. /**
  1604. * Integration test for query caching usigna real cache engine and
  1605. * a formatResults callback
  1606. *
  1607. * @return void
  1608. */
  1609. public function testCacheIntegrationWithFormatResults()
  1610. {
  1611. $table = TableRegistry::get('Articles');
  1612. $query = new Query($this->connection, $table);
  1613. $cacher = new \Cake\Cache\Engine\FileEngine();
  1614. $cacher->init();
  1615. $query
  1616. ->select(['id', 'title'])
  1617. ->formatResults(function ($results) {
  1618. return $results->combine('id', 'title');
  1619. })
  1620. ->cache('my_key', $cacher);
  1621. $expected = $query->toArray();
  1622. $query = new Query($this->connection, $table);
  1623. $results = $query->cache('my_key', $cacher)->toArray();
  1624. $this->assertSame($expected, $results);
  1625. }
  1626. /**
  1627. * Integration test to show filtering associations using contain and a closure
  1628. *
  1629. * @return void
  1630. */
  1631. public function testContainWithClosure()
  1632. {
  1633. $table = TableRegistry::get('authors');
  1634. $table->hasMany('articles');
  1635. $query = new Query($this->connection, $table);
  1636. $query
  1637. ->select()
  1638. ->contain(['articles' => function ($q) {
  1639. return $q->where(['articles.id' => 1]);
  1640. }]);
  1641. $ids = [];
  1642. foreach ($query as $entity) {
  1643. foreach ((array)$entity->articles as $article) {
  1644. $ids[] = $article->id;
  1645. }
  1646. }
  1647. $this->assertEquals([1], array_unique($ids));
  1648. }
  1649. /**
  1650. * Integration test to ensure that filtering associations with the queryBuilder
  1651. * option works.
  1652. *
  1653. * @expectedException \RuntimeException
  1654. * @return void
  1655. */
  1656. public function testContainWithQueryBuilderHasManyError()
  1657. {
  1658. $table = TableRegistry::get('Authors');
  1659. $table->hasMany('Articles');
  1660. $query = new Query($this->connection, $table);
  1661. $query->select()
  1662. ->contain([
  1663. 'Articles' => [
  1664. 'foreignKey' => false,
  1665. 'queryBuilder' => function ($q) {
  1666. return $q->where(['articles.id' => 1]);
  1667. }
  1668. ]
  1669. ]);
  1670. $query->toArray();
  1671. }
  1672. /**
  1673. * Integration test to ensure that filtering associations with the queryBuilder
  1674. * option works.
  1675. *
  1676. * @return void
  1677. */
  1678. public function testContainWithQueryBuilderJoinableAssociation()
  1679. {
  1680. $table = TableRegistry::get('Authors');
  1681. $table->hasOne('Articles');
  1682. $query = new Query($this->connection, $table);
  1683. $query->select()
  1684. ->contain([
  1685. 'Articles' => [
  1686. 'foreignKey' => false,
  1687. 'queryBuilder' => function ($q) {
  1688. return $q->where(['Articles.id' => 1]);
  1689. }
  1690. ]
  1691. ]);
  1692. $result = $query->toArray();
  1693. $this->assertEquals(1, $result[0]->article->id);
  1694. $this->assertEquals(1, $result[1]->article->id);
  1695. $articles = TableRegistry::get('Articles');
  1696. $articles->belongsTo('Authors');
  1697. $query = new Query($this->connection, $articles);
  1698. $query->select()
  1699. ->contain([
  1700. 'Authors' => [
  1701. 'foreignKey' => false,
  1702. 'queryBuilder' => function ($q) {
  1703. return $q->where(['Authors.id' => 1]);
  1704. }
  1705. ]
  1706. ]);
  1707. $result = $query->toArray();
  1708. $this->assertEquals(1, $result[0]->author->id);
  1709. }
  1710. /**
  1711. * Tests the formatResults method
  1712. *
  1713. * @return void
  1714. */
  1715. public function testFormatResults()
  1716. {
  1717. $callback1 = function () {
  1718. };
  1719. $callback2 = function () {
  1720. };
  1721. $table = TableRegistry::get('authors');
  1722. $query = new Query($this->connection, $table);
  1723. $this->assertSame($query, $query->formatResults($callback1));
  1724. $this->assertSame([$callback1], $query->formatResults());
  1725. $this->assertSame($query, $query->formatResults($callback2));
  1726. $this->assertSame([$callback1, $callback2], $query->formatResults());
  1727. $query->formatResults($callback2, true);
  1728. $this->assertSame([$callback2], $query->formatResults());
  1729. $query->formatResults(null, true);
  1730. $this->assertSame([], $query->formatResults());
  1731. $query->formatResults($callback1);
  1732. $query->formatResults($callback2, $query::PREPEND);
  1733. $this->assertSame([$callback2, $callback1], $query->formatResults());
  1734. }
  1735. /**
  1736. * Test fetching results from a qurey with a custom formatter
  1737. *
  1738. * @return void
  1739. */
  1740. public function testQueryWithFormatter()
  1741. {
  1742. $table = TableRegistry::get('authors');
  1743. $query = new Query($this->connection, $table);
  1744. $query->select()->formatResults(function ($results) {
  1745. $this->assertInstanceOf('Cake\ORM\ResultSet', $results);
  1746. return $results->indexBy('id');
  1747. });
  1748. $this->assertEquals([1, 2, 3, 4], array_keys($query->toArray()));
  1749. }
  1750. /**
  1751. * Test fetching results from a qurey with a two custom formatters
  1752. *
  1753. * @return void
  1754. */
  1755. public function testQueryWithStackedFormatters()
  1756. {
  1757. $table = TableRegistry::get('authors');
  1758. $query = new Query($this->connection, $table);
  1759. $query->select()->formatResults(function ($results) {
  1760. $this->assertInstanceOf('Cake\ORM\ResultSet', $results);
  1761. return $results->indexBy('id');
  1762. });
  1763. $query->formatResults(function ($results) {
  1764. return $results->extract('name');
  1765. });
  1766. $expected = [
  1767. 1 => 'mariano',
  1768. 2 => 'nate',
  1769. 3 => 'larry',
  1770. 4 => 'garrett'
  1771. ];
  1772. $this->assertEquals($expected, $query->toArray());
  1773. }
  1774. /**
  1775. * Tests that getting results from a query having a contained association
  1776. * will not attach joins twice if count() is called on it afterwards
  1777. *
  1778. * @return void
  1779. */
  1780. public function testCountWithContainCallingAll()
  1781. {
  1782. $table = TableRegistry::get('articles');
  1783. $table->belongsTo('authors');
  1784. $query = $table->find()
  1785. ->select(['id', 'title'])
  1786. ->contain('authors')
  1787. ->limit(2);
  1788. $results = $query->all();
  1789. $this->assertCount(2, $results);
  1790. $this->assertEquals(3, $query->count());
  1791. }
  1792. /**
  1793. * Tests that it is possible to apply formatters inside the query builder
  1794. * for belongsTo associations
  1795. *
  1796. * @return void
  1797. */
  1798. public function testFormatBelongsToRecords()
  1799. {
  1800. $table = TableRegistry::get('articles');
  1801. $table->belongsTo('authors');
  1802. $query = $table->find()
  1803. ->contain(['authors' => function ($q) {
  1804. return $q
  1805. ->formatResults(function ($authors) {
  1806. return $authors->map(function ($author) {
  1807. $author->idCopy = $author->id;
  1808. return $author;
  1809. });
  1810. })
  1811. ->formatResults(function ($authors) {
  1812. return $authors->map(function ($author) {
  1813. $author->idCopy = $author->idCopy + 2;
  1814. return $author;
  1815. });
  1816. });
  1817. }]);
  1818. $query->formatResults(function ($results) {
  1819. return $results->combine('id', 'author.idCopy');
  1820. });
  1821. $results = $query->toArray();
  1822. $expected = [1 => 3, 2 => 5, 3 => 3];
  1823. $this->assertEquals($expected, $results);
  1824. }
  1825. /**
  1826. * Tests it is possible to apply formatters to deep relations.
  1827. *
  1828. * @return void
  1829. */
  1830. public function testFormatDeepAssocationRecords()
  1831. {
  1832. $table = TableRegistry::get('ArticlesTags');
  1833. $table->belongsTo('Articles');
  1834. $table->association('Articles')->target()->belongsTo('Authors');
  1835. $builder = function ($q) {
  1836. return $q
  1837. ->formatResults(function ($results) {
  1838. return $results->map(function ($result) {
  1839. $result->idCopy = $result->id;
  1840. return $result;
  1841. });
  1842. })
  1843. ->formatResults(function ($results) {
  1844. return $results->map(function ($result) {
  1845. $result->idCopy = $result->idCopy + 2;
  1846. return $result;
  1847. });
  1848. });
  1849. };
  1850. $query = $table->find()
  1851. ->contain(['Articles' => $builder, 'Articles.Authors' => $builder])
  1852. ->order(['Articles.id' => 'ASC']);
  1853. $query->formatResults(function ($results) {
  1854. return $results->map(function ($row) {
  1855. return sprintf(
  1856. '%s - %s - %s',
  1857. $row->tag_id,
  1858. $row->article->idCopy,
  1859. $row->article->author->idCopy
  1860. );
  1861. });
  1862. });
  1863. $expected = ['1 - 3 - 3', '2 - 3 - 3', '1 - 4 - 5', '3 - 4 - 5'];
  1864. $this->assertEquals($expected, $query->toArray());
  1865. }
  1866. /**
  1867. * Tests that formatters cna be applied to deep associations that are fetched using
  1868. * additional queries
  1869. *
  1870. * @return void
  1871. */
  1872. public function testFormatDeepDistantAssociationRecords()
  1873. {
  1874. $table = TableRegistry::get('authors');
  1875. $table->hasMany('articles');
  1876. $articles = $table->association('articles')->target();
  1877. $articles->hasMany('articlesTags');
  1878. $articles->association('articlesTags')->target()->belongsTo('tags');
  1879. $query = $table->find()->contain(['articles.articlesTags.tags' => function ($q) {
  1880. return $q->formatResults(function ($results) {
  1881. return $results->map(function ($tag) {
  1882. $tag->name .= ' - visited';
  1883. return $tag;
  1884. });
  1885. });
  1886. }]);
  1887. $query->mapReduce(function ($row, $key, $mr) {
  1888. foreach ((array)$row->articles as $article) {
  1889. foreach ((array)$article->articles_tags as $articleTag) {
  1890. $mr->emit($articleTag->tag->name);
  1891. }
  1892. }
  1893. });
  1894. $expected = ['tag1 - visited', 'tag2 - visited', 'tag1 - visited', 'tag3 - visited'];
  1895. $this->assertEquals($expected, $query->toArray());
  1896. }
  1897. /**
  1898. * Tests that custom finders are applied to associations when using the proxies
  1899. *
  1900. * @return void
  1901. */
  1902. public function testCustomFinderInBelongsTo()
  1903. {
  1904. $table = TableRegistry::get('ArticlesTags');
  1905. $table->belongsTo('Articles', [
  1906. 'className' => 'TestApp\Model\Table\ArticlesTable',
  1907. 'finder' => 'published'
  1908. ]);
  1909. $result = $table->find()->contain('Articles');
  1910. $this->assertCount(4, $result->extract('article')->filter()->toArray());
  1911. $table->Articles->updateAll(['published' => 'N'], ['1 = 1']);
  1912. $result = $table->find()->contain('Articles');
  1913. $this->assertCount(0, $result->extract('article')->filter()->toArray());
  1914. }
  1915. /**
  1916. * Test finding fields on the non-default table that
  1917. * have the same name as the primary table.
  1918. *
  1919. * @return void
  1920. */
  1921. public function testContainSelectedFields()
  1922. {
  1923. $table = TableRegistry::get('Articles');
  1924. $table->belongsTo('Authors');
  1925. $query = $table->find()
  1926. ->contain(['Authors'])
  1927. ->order(['Authors.id' => 'asc'])
  1928. ->select(['Authors.id']);
  1929. $results = $query->extract('Authors.id')->toList();
  1930. $expected = [1, 1, 3];
  1931. $this->assertEquals($expected, $results);
  1932. }
  1933. /**
  1934. * Tests that it is possible to attach more association when using a query
  1935. * builder for other associations
  1936. *
  1937. * @return void
  1938. */
  1939. public function testContainInAssociationQuery()
  1940. {
  1941. $table = TableRegistry::get('ArticlesTags');
  1942. $table->belongsTo('Articles');
  1943. $table->association('Articles')->target()->belongsTo('Authors');
  1944. $query = $table->find()
  1945. ->order(['Articles.id' => 'ASC'])
  1946. ->contain(['Articles' => function ($q) {
  1947. return $q->contain('Authors');
  1948. }]);
  1949. $results = $query->extract('article.author.name')->toArray();
  1950. $expected = ['mariano', 'mariano', 'larry', 'larry'];
  1951. $this->assertEquals($expected, $results);
  1952. }
  1953. /**
  1954. * Tests that it is possible to apply more `matching` conditions inside query
  1955. * builders for associations
  1956. *
  1957. * @return void
  1958. */
  1959. public function testContainInAssociationMatching()
  1960. {
  1961. $table = TableRegistry::get('authors');
  1962. $table->hasMany('articles');
  1963. $articles = $table->association('articles')->target();
  1964. $articles->hasMany('articlesTags');
  1965. $articles->association('articlesTags')->target()->belongsTo('tags');
  1966. $query = $table->find()->matching('articles.articlesTags', function ($q) {
  1967. return $q->matching('tags', function ($q) {
  1968. return $q->where(['tags.name' => 'tag3']);
  1969. });
  1970. });
  1971. $results = $query->toArray();
  1972. $this->assertCount(1, $results);
  1973. $this->assertEquals('tag3', $results[0]->_matchingData['tags']->name);
  1974. }
  1975. /**
  1976. * Tests __debugInfo
  1977. *
  1978. * @return void
  1979. */
  1980. public function testDebugInfo()
  1981. {
  1982. $table = TableRegistry::get('authors');
  1983. $table->hasMany('articles');
  1984. $query = $table->find()
  1985. ->where(['id > ' => 1])
  1986. ->bufferResults(false)
  1987. ->hydrate(false)
  1988. ->matching('articles')
  1989. ->applyOptions(['foo' => 'bar'])
  1990. ->formatResults(function ($results) {
  1991. return $results;
  1992. })
  1993. ->mapReduce(function ($item, $key, $mr) {
  1994. $mr->emit($item);
  1995. });
  1996. $expected = [
  1997. 'sql' => $query->sql(),
  1998. 'params' => $query->valueBinder()->bindings(),
  1999. 'defaultTypes' => [
  2000. 'authors.id' => 'integer',
  2001. 'id' => 'integer',
  2002. 'authors.name' => 'string',
  2003. 'name' => 'string'
  2004. ],
  2005. 'decorators' => 0,
  2006. 'executed' => false,
  2007. 'hydrate' => false,
  2008. 'buffered' => false,
  2009. 'formatters' => 1,
  2010. 'mapReducers' => 1,
  2011. 'contain' => [],
  2012. 'matching' => [
  2013. 'articles' => [
  2014. 'queryBuilder' => null,
  2015. 'matching' => true
  2016. ]
  2017. ],
  2018. 'extraOptions' => ['foo' => 'bar'],
  2019. 'repository' => $table
  2020. ];
  2021. $this->assertSame($expected, $query->__debugInfo());
  2022. }
  2023. /**
  2024. * Tests that the eagerLoaded function works and is transmitted correctly to eagerly
  2025. * loaded associations
  2026. *
  2027. * @return void
  2028. */
  2029. public function testEagerLoaded()
  2030. {
  2031. $table = TableRegistry::get('authors');
  2032. $table->hasMany('articles');
  2033. $query = $table->find()->contain(['articles' => function ($q) {
  2034. $this->assertTrue($q->eagerLoaded());
  2035. return $q;
  2036. }]);
  2037. $this->assertFalse($query->eagerLoaded());
  2038. $table->eventManager()->attach(function ($e, $q, $o, $primary) {
  2039. $this->assertTrue($primary);
  2040. }, 'Model.beforeFind');
  2041. TableRegistry::get('articles')
  2042. ->eventManager()->attach(function ($e, $q, $o, $primary) {
  2043. $this->assertFalse($primary);
  2044. }, 'Model.beforeFind');
  2045. $query->all();
  2046. }
  2047. /**
  2048. * Tests that columns from manual joins are also contained in the result set
  2049. *
  2050. * @return void
  2051. */
  2052. public function testColumnsFromJoin()
  2053. {
  2054. $table = TableRegistry::get('articles');
  2055. $results = $table->find()
  2056. ->select(['title', 'person.name'])
  2057. ->join([
  2058. 'person' => [
  2059. 'table' => 'authors',
  2060. 'conditions' => ['person.id = articles.author_id']
  2061. ]
  2062. ])
  2063. ->order(['articles.id' => 'ASC'])
  2064. ->hydrate(false)
  2065. ->toArray();
  2066. $expected = [
  2067. ['title' => 'First Article', 'person' => ['name' => 'mariano']],
  2068. ['title' => 'Second Article', 'person' => ['name' => 'larry']],
  2069. ['title' => 'Third Article', 'person' => ['name' => 'mariano']],
  2070. ];
  2071. $this->assertSame($expected, $results);
  2072. }
  2073. /**
  2074. * Tests that it is possible to use the same association aliases in the association
  2075. * chain for contain
  2076. *
  2077. * @dataProvider strategiesProviderBelongsTo
  2078. * @return void
  2079. */
  2080. public function testRepeatedAssociationAliases($strategy)
  2081. {
  2082. $table = TableRegistry::get('ArticlesTags');
  2083. $table->belongsTo('Articles', ['strategy' => $strategy]);
  2084. $table->belongsTo('Tags', ['strategy' => $strategy]);
  2085. TableRegistry::get('Tags')->belongsToMany('Articles');
  2086. $results = $table
  2087. ->find()
  2088. ->contain(['Articles', 'Tags.Articles'])
  2089. ->hydrate(false)
  2090. ->toArray();
  2091. $this->assertNotEmpty($results[0]['tag']['articles']);
  2092. $this->assertNotEmpty($results[0]['article']);
  2093. $this->assertNotEmpty($results[1]['tag']['articles']);
  2094. $this->assertNotEmpty($results[1]['article']);
  2095. $this->assertNotEmpty($results[2]['tag']['articles']);
  2096. $this->assertNotEmpty($results[2]['article']);
  2097. }
  2098. /**
  2099. * Tests that a hasOne association using the select strategy will still have the
  2100. * key present in the results when no match is found
  2101. *
  2102. * @return void
  2103. */
  2104. public function testAssociationKeyPresent()
  2105. {
  2106. $table = TableRegistry::get('Articles');
  2107. $table->hasOne('ArticlesTags', ['strategy' => 'select']);
  2108. $article = $table->find()->where(['id' => 3])
  2109. ->hydrate(false)
  2110. ->contain('ArticlesTags')
  2111. ->first();
  2112. $this->assertNull($article['articles_tag']);
  2113. }
  2114. /**
  2115. * Tests that queries can be serialized to JSON to get the results
  2116. *
  2117. * @return void
  2118. */
  2119. public function testJsonSerialize()
  2120. {
  2121. $table = TableRegistry::get('Articles');
  2122. $this->assertEquals(
  2123. json_encode($table->find()),
  2124. json_encode($table->find()->toArray())
  2125. );
  2126. }
  2127. /**
  2128. * Test that addFields() works in the basic case.
  2129. *
  2130. * @return void
  2131. */
  2132. public function testAutoFields()
  2133. {
  2134. $table = TableRegistry::get('Articles');
  2135. $result = $table->find('all')
  2136. ->select(['myField' => '(SELECT 20)'])
  2137. ->autoFields(true)
  2138. ->hydrate(false)
  2139. ->first();
  2140. $this->assertArrayHasKey('myField', $result);
  2141. $this->assertArrayHasKey('id', $result);
  2142. $this->assertArrayHasKey('title', $result);
  2143. }
  2144. /**
  2145. * Test autoFields with auto fields.
  2146. *
  2147. * @return void
  2148. */
  2149. public function testAutoFieldsWithAssociations()
  2150. {
  2151. $table = TableRegistry::get('Articles');
  2152. $table->belongsTo('Authors');
  2153. $result = $table->find()
  2154. ->select(['myField' => '(SELECT 2 + 2)'])
  2155. ->autoFields(true)
  2156. ->hydrate(false)
  2157. ->contain('Authors')
  2158. ->first();
  2159. $this->assertArrayHasKey('myField', $result);
  2160. $this->assertArrayHasKey('title', $result);
  2161. $this->assertArrayHasKey('author', $result);
  2162. $this->assertNotNull($result['author']);
  2163. $this->assertArrayHasKey('name', $result['author']);
  2164. }
  2165. /**
  2166. * Test autoFields in contain query builder
  2167. *
  2168. * @return void
  2169. */
  2170. public function testAutoFieldsWithContainQueryBuilder()
  2171. {
  2172. $table = TableRegistry::get('Articles');
  2173. $table->belongsTo('Authors');
  2174. $result = $table->find()
  2175. ->select(['myField' => '(SELECT 2 + 2)'])
  2176. ->autoFields(true)
  2177. ->hydrate(false)
  2178. ->contain(['Authors' => function ($q) {
  2179. return $q->select(['compute' => '(SELECT 2 + 20)'])
  2180. ->autoFields(true);
  2181. }])
  2182. ->first();
  2183. $this->assertArrayHasKey('myField', $result);
  2184. $this->assertArrayHasKey('title', $result);
  2185. $this->assertArrayHasKey('author', $result);
  2186. $this->assertNotNull($result['author']);
  2187. $this->assertArrayHasKey('name', $result['author']);
  2188. $this->assertArrayHasKey('compute', $result);
  2189. }
  2190. /**
  2191. * Test that autofields works with count()
  2192. *
  2193. * @return void
  2194. */
  2195. public function testAutoFieldsCount()
  2196. {
  2197. $table = TableRegistry::get('Articles');
  2198. $result = $table->find()
  2199. ->select(['myField' => '(SELECT (2 + 2))'])
  2200. ->autoFields(true)
  2201. ->count();
  2202. $this->assertEquals(3, $result);
  2203. }
  2204. /**
  2205. * test that cleanCopy makes a cleaned up clone.
  2206. *
  2207. * @return void
  2208. */
  2209. public function testCleanCopy()
  2210. {
  2211. $table = TableRegistry::get('Articles');
  2212. $table->hasMany('Comments');
  2213. $query = $table->find();
  2214. $query->offset(10)
  2215. ->limit(1)
  2216. ->order(['Articles.id' => 'DESC'])
  2217. ->contain(['Comments']);
  2218. $copy = $query->cleanCopy();
  2219. $this->assertNotSame($copy, $query);
  2220. $this->assertNotSame($copy->eagerLoader(), $query->eagerLoader());
  2221. $this->assertNotEmpty($copy->eagerLoader()->contain());
  2222. $this->assertNull($copy->clause('offset'));
  2223. $this->assertNull($copy->clause('limit'));
  2224. $this->assertNull($copy->clause('order'));
  2225. }
  2226. /**
  2227. * test that cleanCopy retains bindings
  2228. *
  2229. * @return void
  2230. */
  2231. public function testCleanCopyRetainsBindings()
  2232. {
  2233. $table = TableRegistry::get('Articles');
  2234. $query = $table->find();
  2235. $query->offset(10)
  2236. ->limit(1)
  2237. ->where(['Articles.id BETWEEN :start AND :end'])
  2238. ->order(['Articles.id' => 'DESC'])
  2239. ->bind(':start', 1)
  2240. ->bind(':end', 2);
  2241. $copy = $query->cleanCopy();
  2242. $this->assertNotEmpty($copy->valueBinder()->bindings());
  2243. }
  2244. /**
  2245. * test that cleanCopy makes a cleaned up clone with a beforeFind.
  2246. *
  2247. * @return void
  2248. */
  2249. public function testCleanCopyBeforeFind()
  2250. {
  2251. $table = TableRegistry::get('Articles');
  2252. $table->hasMany('Comments');
  2253. $table->eventManager()
  2254. ->attach(function ($event, $query) {
  2255. $query
  2256. ->limit(5)
  2257. ->order(['Articles.title' => 'DESC']);
  2258. }, 'Model.beforeFind');
  2259. $query = $table->find();
  2260. $query->offset(10)
  2261. ->limit(1)
  2262. ->order(['Articles.id' => 'DESC'])
  2263. ->contain(['Comments']);
  2264. $copy = $query->cleanCopy();
  2265. $this->assertNotSame($copy, $query);
  2266. $this->assertNull($copy->clause('offset'));
  2267. $this->assertNull($copy->clause('limit'));
  2268. $this->assertNull($copy->clause('order'));
  2269. }
  2270. /**
  2271. * Test that finder options sent through via contain are sent to custom finder.
  2272. *
  2273. * @return void
  2274. */
  2275. public function testContainFinderCanSpecifyOptions()
  2276. {
  2277. $table = TableRegistry::get('Articles');
  2278. $table->belongsTo(
  2279. 'Authors',
  2280. ['className' => 'TestApp\Model\Table\AuthorsTable']
  2281. );
  2282. $authorId = 1;
  2283. $resultWithoutAuthor = $table->find('all')
  2284. ->where(['Articles.author_id' => $authorId])
  2285. ->contain([
  2286. 'Authors' => [
  2287. 'finder' => ['byAuthor' => ['author_id' => 2]]
  2288. ]
  2289. ]);
  2290. $resultWithAuthor = $table->find('all')
  2291. ->where(['Articles.author_id' => $authorId])
  2292. ->contain([
  2293. 'Authors' => [
  2294. 'finder' => ['byAuthor' => ['author_id' => $authorId]]
  2295. ]
  2296. ]);
  2297. $this->assertEmpty($resultWithoutAuthor->first()['author']);
  2298. $this->assertEquals($authorId, $resultWithAuthor->first()['author']['id']);
  2299. }
  2300. /**
  2301. * Tests that it is possible to bind arguments to a query and it will return the right
  2302. * results
  2303. *
  2304. * @return void
  2305. */
  2306. public function testCustomBindings()
  2307. {
  2308. $table = TableRegistry::get('Articles');
  2309. $query = $table->find()->where(['id >' => 1]);
  2310. $query->where(function ($exp) {
  2311. return $exp->add('author_id = :author');
  2312. });
  2313. $query->bind(':author', 1, 'integer');
  2314. $this->assertEquals(1, $query->count());
  2315. $this->assertEquals(3, $query->first()->id);
  2316. }
  2317. /**
  2318. * Tests that it is possible to pass a custom join type for an association when
  2319. * using contain
  2320. *
  2321. * @return void
  2322. */
  2323. public function testContainWithCustomJoinType()
  2324. {
  2325. $table = TableRegistry::get('Articles');
  2326. $table->belongsTo('Authors');
  2327. $articles = $table->find()
  2328. ->contain([
  2329. 'Authors' => [
  2330. 'joinType' => 'inner',
  2331. 'conditions' => ['Authors.id' => 3]
  2332. ]
  2333. ])
  2334. ->toArray();
  2335. $this->assertCount(1, $articles);
  2336. $this->assertEquals(3, $articles[0]->author->id);
  2337. }
  2338. /**
  2339. * Tests that it is possible to override the contain strategy using the
  2340. * containments array. In this case, no inner join will be made and for that
  2341. * reason, the parent association will not be filtered as the strategy changed
  2342. * from join to select.
  2343. *
  2344. * @return void
  2345. */
  2346. public function testContainWithStrategyOverride()
  2347. {
  2348. $table = TableRegistry::get('Articles');
  2349. $table->belongsTo('Authors', [
  2350. 'joinType' => 'INNER'
  2351. ]);
  2352. $articles = $table->find()
  2353. ->contain([
  2354. 'Authors' => [
  2355. 'strategy' => 'select',
  2356. 'conditions' => ['Authors.id' => 3]
  2357. ]
  2358. ])
  2359. ->toArray();
  2360. $this->assertCount(3, $articles);
  2361. $this->assertEquals(3, $articles[1]->author->id);
  2362. $this->assertNull($articles[0]->author);
  2363. $this->assertNull($articles[2]->author);
  2364. }
  2365. /**
  2366. * Tests that it is possible to call matching and contain on the same
  2367. * association.
  2368. *
  2369. * @return void
  2370. */
  2371. public function testMatchingWithContain()
  2372. {
  2373. $query = new Query($this->connection, $this->table);
  2374. $table = TableRegistry::get('authors');
  2375. $table->hasMany('articles');
  2376. TableRegistry::get('articles')->belongsToMany('tags');
  2377. $result = $query->repository($table)
  2378. ->select()
  2379. ->matching('articles.tags', function ($q) {
  2380. return $q->where(['tags.id' => 2]);
  2381. })
  2382. ->contain('articles')
  2383. ->first();
  2384. $this->assertEquals(1, $result->id);
  2385. $this->assertCount(2, $result->articles);
  2386. $this->assertEquals(2, $result->_matchingData['tags']->id);
  2387. }
  2388. /**
  2389. * Tests that it is possible to call matching and contain on the same
  2390. * association with only one level of depth.
  2391. *
  2392. * @return void
  2393. */
  2394. public function testNotSoFarMatchingWithContainOnTheSameAssociation()
  2395. {
  2396. $table = TableRegistry::get('articles');
  2397. $table->belongsToMany('tags');
  2398. $result = $table->find()
  2399. ->matching('tags', function ($q) {
  2400. return $q->where(['tags.id' => 2]);
  2401. })
  2402. ->contain('tags')
  2403. ->first();
  2404. $this->assertEquals(1, $result->id);
  2405. $this->assertCount(2, $result->tags);
  2406. $this->assertEquals(2, $result->_matchingData['tags']->id);
  2407. }
  2408. /**
  2409. * Tests that isEmpty() can be called on a query
  2410. *
  2411. * @return void
  2412. */
  2413. public function testIsEmpty()
  2414. {
  2415. $table = TableRegistry::get('articles');
  2416. $this->assertFalse($table->find()->isEmpty());
  2417. $this->assertTrue($table->find()->where(['id' => -1])->isEmpty());
  2418. }
  2419. }