QueryTest.php 115 KB

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