QueryTest.php 97 KB

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