QueryTest.php 101 KB

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