QueryTest.php 96 KB

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