QueryTest.php 114 KB

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