QueryTest.php 100 KB

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