QueryTest.php 109 KB

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