QueryTest.php 100 KB

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