QueryTest.php 97 KB

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