QueryTest.php 102 KB

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