QueryTest.php 100 KB

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