QueryTest.php 103 KB

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