QueryTest.php 114 KB

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