QueryTest.php 100 KB

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