QueryTest.php 117 KB

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