QueryTest.php 101 KB

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