QueryTest.php 95 KB

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