QueryTest.php 77 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since 3.0.0
  13. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Test\TestCase\ORM;
  16. use Cake\Database\Expression\IdentifierExpression;
  17. use Cake\Database\Expression\OrderByExpression;
  18. use Cake\Database\Expression\QueryExpression;
  19. use Cake\Database\TypeMap;
  20. use Cake\Datasource\ConnectionManager;
  21. use Cake\ORM\Query;
  22. use Cake\ORM\ResultSet;
  23. use Cake\ORM\Table;
  24. use Cake\ORM\TableRegistry;
  25. use Cake\TestSuite\TestCase;
  26. /**
  27. * Tests Query class
  28. */
  29. class QueryTest extends TestCase
  30. {
  31. /**
  32. * Fixture to be used
  33. *
  34. * @var array
  35. */
  36. public $fixtures = ['core.articles', 'core.authors', 'core.tags',
  37. 'core.articles_tags', 'core.posts'];
  38. /**
  39. * setUp method
  40. *
  41. * @return void
  42. */
  43. public function setUp()
  44. {
  45. parent::setUp();
  46. $this->connection = ConnectionManager::get('test');
  47. $schema = [
  48. 'id' => ['type' => 'integer'],
  49. '_constraints' => [
  50. 'primary' => ['type' => 'primary', 'columns' => ['id']]
  51. ]
  52. ];
  53. $schema1 = [
  54. 'id' => ['type' => 'integer'],
  55. 'name' => ['type' => 'string'],
  56. 'phone' => ['type' => 'string'],
  57. '_constraints' => [
  58. 'primary' => ['type' => 'primary', 'columns' => ['id']]
  59. ]
  60. ];
  61. $schema2 = [
  62. 'id' => ['type' => 'integer'],
  63. 'total' => ['type' => 'string'],
  64. 'placed' => ['type' => 'datetime'],
  65. '_constraints' => [
  66. 'primary' => ['type' => 'primary', 'columns' => ['id']]
  67. ]
  68. ];
  69. $this->table = $table = TableRegistry::get('foo', ['schema' => $schema]);
  70. $clients = TableRegistry::get('clients', ['schema' => $schema1]);
  71. $orders = TableRegistry::get('orders', ['schema' => $schema2]);
  72. $companies = TableRegistry::get('companies', ['schema' => $schema, 'table' => 'organizations']);
  73. $orderTypes = TableRegistry::get('orderTypes', ['schema' => $schema]);
  74. $stuff = TableRegistry::get('stuff', ['schema' => $schema, 'table' => 'things']);
  75. $stuffTypes = TableRegistry::get('stuffTypes', ['schema' => $schema]);
  76. $categories = TableRegistry::get('categories', ['schema' => $schema]);
  77. $table->belongsTo('clients');
  78. $clients->hasOne('orders');
  79. $clients->belongsTo('companies');
  80. $orders->belongsTo('orderTypes');
  81. $orders->hasOne('stuff');
  82. $stuff->belongsTo('stuffTypes');
  83. $companies->belongsTo('categories');
  84. $this->fooTypeMap = new TypeMap(['foo.id' => 'integer', 'id' => 'integer']);
  85. }
  86. /**
  87. * tearDown method
  88. *
  89. * @return void
  90. */
  91. public function tearDown()
  92. {
  93. parent::tearDown();
  94. TableRegistry::clear();
  95. }
  96. /**
  97. * Provides strategies for associations that can be joined
  98. *
  99. * @return void
  100. */
  101. public function internalStategiesProvider()
  102. {
  103. return [['join'], ['select'], ['subquery']];
  104. }
  105. /**
  106. * Tests that results are grouped correctly when using contain()
  107. * and results are not hydrated
  108. *
  109. * @dataProvider internalStategiesProvider
  110. * @return void
  111. */
  112. public function testContainResultFetchingOneLevel($strategy)
  113. {
  114. $table = TableRegistry::get('articles', ['table' => 'articles']);
  115. $table->belongsTo('authors', ['strategy' => $strategy]);
  116. $query = new Query($this->connection, $table);
  117. $results = $query->select()
  118. ->contain('authors')
  119. ->hydrate(false)
  120. ->order(['articles.id' => 'asc'])
  121. ->toArray();
  122. $expected = [
  123. [
  124. 'id' => 1,
  125. 'title' => 'First Article',
  126. 'body' => 'First Article Body',
  127. 'author_id' => 1,
  128. 'published' => 'Y',
  129. 'author' => [
  130. 'id' => 1,
  131. 'name' => 'mariano'
  132. ]
  133. ],
  134. [
  135. 'id' => 2,
  136. 'title' => 'Second Article',
  137. 'body' => 'Second Article Body',
  138. 'author_id' => 3,
  139. 'published' => 'Y',
  140. 'author' => [
  141. 'id' => 3,
  142. 'name' => 'larry'
  143. ]
  144. ],
  145. [
  146. 'id' => 3,
  147. 'title' => 'Third Article',
  148. 'body' => 'Third Article Body',
  149. 'author_id' => 1,
  150. 'published' => 'Y',
  151. 'author' => [
  152. 'id' => 1,
  153. 'name' => 'mariano'
  154. ]
  155. ],
  156. ];
  157. $this->assertEquals($expected, $results);
  158. }
  159. /**
  160. * Data provider for the two types of strategies HasMany implements
  161. *
  162. * @return void
  163. */
  164. public function strategiesProvider()
  165. {
  166. return [['subquery'], ['select']];
  167. }
  168. /**
  169. * Tests that HasMany associations are correctly eager loaded and results
  170. * correctly nested when no hydration is used
  171. * Also that the query object passes the correct parent model keys to the
  172. * association objects in order to perform eager loading with select strategy
  173. *
  174. * @dataProvider strategiesProvider
  175. * @return void
  176. */
  177. public function testHasManyEagerLoadingNoHydration($strategy)
  178. {
  179. $table = TableRegistry::get('authors');
  180. TableRegistry::get('articles');
  181. $table->hasMany('articles', [
  182. 'propertyName' => 'articles',
  183. 'strategy' => $strategy,
  184. 'sort' => ['articles.id' => 'asc']
  185. ]);
  186. $query = new Query($this->connection, $table);
  187. $results = $query->select()
  188. ->contain('articles')
  189. ->hydrate(false)
  190. ->toArray();
  191. $expected = [
  192. [
  193. 'id' => 1,
  194. 'name' => 'mariano',
  195. 'articles' => [
  196. [
  197. 'id' => 1,
  198. 'title' => 'First Article',
  199. 'body' => 'First Article Body',
  200. 'author_id' => 1,
  201. 'published' => 'Y',
  202. ],
  203. [
  204. 'id' => 3,
  205. 'title' => 'Third Article',
  206. 'body' => 'Third Article Body',
  207. 'author_id' => 1,
  208. 'published' => 'Y',
  209. ],
  210. ]
  211. ],
  212. [
  213. 'id' => 2,
  214. 'name' => 'nate',
  215. 'articles' => [],
  216. ],
  217. [
  218. 'id' => 3,
  219. 'name' => 'larry',
  220. 'articles' => [
  221. [
  222. 'id' => 2,
  223. 'title' => 'Second Article',
  224. 'body' => 'Second Article Body',
  225. 'author_id' => 3,
  226. 'published' => 'Y'
  227. ]
  228. ]
  229. ],
  230. [
  231. 'id' => 4,
  232. 'name' => 'garrett',
  233. 'articles' => [],
  234. ]
  235. ];
  236. $this->assertEquals($expected, $results);
  237. $results = $query->repository($table)
  238. ->select()
  239. ->contain(['articles' => ['conditions' => ['articles.id' => 2]]])
  240. ->hydrate(false)
  241. ->toArray();
  242. $expected[0]['articles'] = [];
  243. $this->assertEquals($expected, $results);
  244. $this->assertEquals($table->association('articles')->strategy(), $strategy);
  245. }
  246. /**
  247. * Tests that it is possible to count results containing hasMany associations
  248. * both hydrating and not hydrating the results.
  249. *
  250. * @dataProvider strategiesProvider
  251. * @return void
  252. */
  253. public function testHasManyEagerLoadingCount($strategy)
  254. {
  255. $table = TableRegistry::get('authors');
  256. TableRegistry::get('articles');
  257. $table->hasMany('articles', [
  258. 'property' => 'articles',
  259. 'strategy' => $strategy,
  260. 'sort' => ['articles.id' => 'asc']
  261. ]);
  262. $query = new Query($this->connection, $table);
  263. $query = $query->select()
  264. ->contain('articles');
  265. $expected = 4;
  266. $results = $query->hydrate(false)
  267. ->count();
  268. $this->assertEquals($expected, $results);
  269. $results = $query->hydrate(true)
  270. ->count();
  271. $this->assertEquals($expected, $results);
  272. }
  273. /**
  274. * Tests that it is possible to set fields & order in a hasMany result set
  275. *
  276. * @dataProvider strategiesProvider
  277. * @return void
  278. */
  279. public function testHasManyEagerLoadingFieldsAndOrderNoHydration($strategy)
  280. {
  281. $table = TableRegistry::get('authors');
  282. TableRegistry::get('articles');
  283. $table->hasMany('articles', ['propertyName' => 'articles'] + compact('strategy'));
  284. $query = new Query($this->connection, $table);
  285. $results = $query->select()
  286. ->contain([
  287. 'articles' => [
  288. 'fields' => ['title', 'author_id'],
  289. 'sort' => ['articles.id' => 'DESC']
  290. ]
  291. ])
  292. ->hydrate(false)
  293. ->toArray();
  294. $expected = [
  295. [
  296. 'id' => 1,
  297. 'name' => 'mariano',
  298. 'articles' => [
  299. ['title' => 'Third Article', 'author_id' => 1],
  300. ['title' => 'First Article', 'author_id' => 1],
  301. ]
  302. ],
  303. [
  304. 'id' => 2,
  305. 'name' => 'nate',
  306. 'articles' => [],
  307. ],
  308. [
  309. 'id' => 3,
  310. 'name' => 'larry',
  311. 'articles' => [
  312. ['title' => 'Second Article', 'author_id' => 3],
  313. ]
  314. ],
  315. [
  316. 'id' => 4,
  317. 'name' => 'garrett',
  318. 'articles' => [],
  319. ],
  320. ];
  321. $this->assertEquals($expected, $results);
  322. }
  323. /**
  324. * Tests that deep associations can be eagerly loaded
  325. *
  326. * @dataProvider strategiesProvider
  327. * @return void
  328. */
  329. public function testHasManyEagerLoadingDeep($strategy)
  330. {
  331. $table = TableRegistry::get('authors');
  332. $article = TableRegistry::get('articles');
  333. $table->hasMany('articles', [
  334. 'propertyName' => 'articles',
  335. 'strategy' => $strategy,
  336. 'sort' => ['articles.id' => 'asc']
  337. ]);
  338. $article->belongsTo('authors');
  339. $query = new Query($this->connection, $table);
  340. $results = $query->select()
  341. ->contain(['articles' => ['authors']])
  342. ->hydrate(false)
  343. ->toArray();
  344. $expected = [
  345. [
  346. 'id' => 1,
  347. 'name' => 'mariano',
  348. 'articles' => [
  349. [
  350. 'id' => 1,
  351. 'title' => 'First Article',
  352. 'author_id' => 1,
  353. 'body' => 'First Article Body',
  354. 'published' => 'Y',
  355. 'author' => ['id' => 1, 'name' => 'mariano']
  356. ],
  357. [
  358. 'id' => 3,
  359. 'title' => 'Third Article',
  360. 'author_id' => 1,
  361. 'body' => 'Third Article Body',
  362. 'published' => 'Y',
  363. 'author' => ['id' => 1, 'name' => 'mariano']
  364. ],
  365. ]
  366. ],
  367. [
  368. 'id' => 2,
  369. 'name' => 'nate',
  370. 'articles' => [],
  371. ],
  372. [
  373. 'id' => 3,
  374. 'name' => 'larry',
  375. 'articles' => [
  376. [
  377. 'id' => 2,
  378. 'title' => 'Second Article',
  379. 'author_id' => 3,
  380. 'body' => 'Second Article Body',
  381. 'published' => 'Y',
  382. 'author' => ['id' => 3, 'name' => 'larry']
  383. ],
  384. ]
  385. ],
  386. [
  387. 'id' => 4,
  388. 'name' => 'garrett',
  389. 'articles' => [],
  390. ]
  391. ];
  392. $this->assertEquals($expected, $results);
  393. }
  394. /**
  395. * Tests that hasMany associations can be loaded even when related to a secondary
  396. * model in the query
  397. *
  398. * @dataProvider strategiesProvider
  399. * @return void
  400. */
  401. public function testHasManyEagerLoadingFromSecondaryTable($strategy)
  402. {
  403. $author = TableRegistry::get('authors');
  404. $article = TableRegistry::get('articles');
  405. $post = TableRegistry::get('posts');
  406. $author->hasMany('posts', compact('strategy'));
  407. $article->belongsTo('authors');
  408. $query = new Query($this->connection, $article);
  409. $results = $query->select()
  410. ->contain(['authors' => ['posts']])
  411. ->order(['articles.id' => 'ASC'])
  412. ->hydrate(false)
  413. ->toArray();
  414. $expected = [
  415. [
  416. 'id' => 1,
  417. 'title' => 'First Article',
  418. 'body' => 'First Article Body',
  419. 'author_id' => 1,
  420. 'published' => 'Y',
  421. 'author' => [
  422. 'id' => 1,
  423. 'name' => 'mariano',
  424. 'posts' => [
  425. [
  426. 'id' => '1',
  427. 'title' => 'First Post',
  428. 'body' => 'First Post Body',
  429. 'author_id' => 1,
  430. 'published' => 'Y',
  431. ],
  432. [
  433. 'id' => '3',
  434. 'title' => 'Third Post',
  435. 'body' => 'Third Post Body',
  436. 'author_id' => 1,
  437. 'published' => 'Y',
  438. ],
  439. ]
  440. ]
  441. ],
  442. [
  443. 'id' => 2,
  444. 'title' => 'Second Article',
  445. 'body' => 'Second Article Body',
  446. 'author_id' => 3,
  447. 'published' => 'Y',
  448. 'author' => [
  449. 'id' => 3,
  450. 'name' => 'larry',
  451. 'posts' => [
  452. [
  453. 'id' => 2,
  454. 'title' => 'Second Post',
  455. 'body' => 'Second Post Body',
  456. 'author_id' => 3,
  457. 'published' => 'Y',
  458. ]
  459. ]
  460. ]
  461. ],
  462. [
  463. 'id' => 3,
  464. 'title' => 'Third Article',
  465. 'body' => 'Third Article Body',
  466. 'author_id' => 1,
  467. 'published' => 'Y',
  468. 'author' => [
  469. 'id' => 1,
  470. 'name' => 'mariano',
  471. 'posts' => [
  472. [
  473. 'id' => '1',
  474. 'title' => 'First Post',
  475. 'body' => 'First Post Body',
  476. 'author_id' => 1,
  477. 'published' => 'Y',
  478. ],
  479. [
  480. 'id' => '3',
  481. 'title' => 'Third Post',
  482. 'body' => 'Third Post Body',
  483. 'author_id' => 1,
  484. 'published' => 'Y',
  485. ],
  486. ]
  487. ]
  488. ],
  489. ];
  490. $this->assertEquals($expected, $results);
  491. }
  492. /**
  493. * Tests that BelongsToMany associations are correctly eager loaded.
  494. * Also that the query object passes the correct parent model keys to the
  495. * association objects in order to perform eager loading with select strategy
  496. *
  497. * @dataProvider strategiesProvider
  498. * @return void
  499. */
  500. public function testBelongsToManyEagerLoadingNoHydration($strategy)
  501. {
  502. $table = TableRegistry::get('Articles');
  503. TableRegistry::get('Tags');
  504. TableRegistry::get('ArticlesTags', [
  505. 'table' => 'articles_tags'
  506. ]);
  507. $table->belongsToMany('Tags', ['strategy' => $strategy]);
  508. $query = new Query($this->connection, $table);
  509. $results = $query->select()->contain('Tags')->hydrate(false)->toArray();
  510. $expected = [
  511. [
  512. 'id' => 1,
  513. 'author_id' => 1,
  514. 'title' => 'First Article',
  515. 'body' => 'First Article Body',
  516. 'published' => 'Y',
  517. 'tags' => [
  518. [
  519. 'id' => 1,
  520. 'name' => 'tag1',
  521. '_joinData' => ['article_id' => 1, 'tag_id' => 1]
  522. ],
  523. [
  524. 'id' => 2,
  525. 'name' => 'tag2',
  526. '_joinData' => ['article_id' => 1, 'tag_id' => 2]
  527. ]
  528. ]
  529. ],
  530. [
  531. 'id' => 2,
  532. 'title' => 'Second Article',
  533. 'body' => 'Second Article Body',
  534. 'author_id' => 3,
  535. 'published' => 'Y',
  536. 'tags' => [
  537. [
  538. 'id' => 1,
  539. 'name' => 'tag1',
  540. '_joinData' => ['article_id' => 2, 'tag_id' => 1]
  541. ],
  542. [
  543. 'id' => 3,
  544. 'name' => 'tag3',
  545. '_joinData' => ['article_id' => 2, 'tag_id' => 3]
  546. ]
  547. ]
  548. ],
  549. [
  550. 'id' => 3,
  551. 'title' => 'Third Article',
  552. 'body' => 'Third Article Body',
  553. 'author_id' => 1,
  554. 'published' => 'Y',
  555. 'tags' => [],
  556. ],
  557. ];
  558. $this->assertEquals($expected, $results);
  559. $results = $query->select()
  560. ->contain(['Tags' => ['conditions' => ['Tags.id' => 3]]])
  561. ->hydrate(false)
  562. ->toArray();
  563. $expected = [
  564. [
  565. 'id' => 1,
  566. 'author_id' => 1,
  567. 'title' => 'First Article',
  568. 'body' => 'First Article Body',
  569. 'published' => 'Y',
  570. 'tags' => [],
  571. ],
  572. [
  573. 'id' => 2,
  574. 'title' => 'Second Article',
  575. 'body' => 'Second Article Body',
  576. 'author_id' => 3,
  577. 'published' => 'Y',
  578. 'tags' => [
  579. [
  580. 'id' => 3,
  581. 'name' => 'tag3',
  582. '_joinData' => ['article_id' => 2, 'tag_id' => 3]
  583. ]
  584. ]
  585. ],
  586. [
  587. 'id' => 3,
  588. 'title' => 'Third Article',
  589. 'body' => 'Third Article Body',
  590. 'author_id' => 1,
  591. 'published' => 'Y',
  592. 'tags' => [],
  593. ],
  594. ];
  595. $this->assertEquals($expected, $results);
  596. $this->assertEquals($table->association('Tags')->strategy(), $strategy);
  597. }
  598. /**
  599. * Tests that tables results can be filtered by the result of a HasMany
  600. *
  601. * @return void
  602. */
  603. public function testFilteringByHasManyNoHydration()
  604. {
  605. $query = new Query($this->connection, $this->table);
  606. $table = TableRegistry::get('authors');
  607. TableRegistry::get('articles');
  608. $table->hasMany('articles');
  609. $results = $query->repository($table)
  610. ->select()
  611. ->hydrate(false)
  612. ->matching('articles', function ($q) {
  613. return $q->where(['articles.id' => 2]);
  614. })
  615. ->toArray();
  616. $expected = [
  617. [
  618. 'id' => 3,
  619. 'name' => 'larry',
  620. '_matchingData' => [
  621. 'articles' => [
  622. 'id' => 2,
  623. 'title' => 'Second Article',
  624. 'body' => 'Second Article Body',
  625. 'author_id' => 3,
  626. 'published' => 'Y',
  627. ]
  628. ]
  629. ]
  630. ];
  631. $this->assertEquals($expected, $results);
  632. }
  633. /**
  634. * Tests that BelongsToMany associations are correctly eager loaded.
  635. * Also that the query object passes the correct parent model keys to the
  636. * association objects in order to perform eager loading with select strategy
  637. *
  638. * @return void
  639. */
  640. public function testFilteringByBelongsToManyNoHydration()
  641. {
  642. $query = new Query($this->connection, $this->table);
  643. $table = TableRegistry::get('Articles');
  644. TableRegistry::get('Tags');
  645. TableRegistry::get('ArticlesTags', [
  646. 'table' => 'articles_tags'
  647. ]);
  648. $table->belongsToMany('Tags');
  649. $results = $query->repository($table)->select()
  650. ->matching('Tags', function ($q) {
  651. return $q->where(['Tags.id' => 3]);
  652. })
  653. ->hydrate(false)
  654. ->toArray();
  655. $expected = [
  656. [
  657. 'id' => 2,
  658. 'author_id' => 3,
  659. 'title' => 'Second Article',
  660. 'body' => 'Second Article Body',
  661. 'published' => 'Y',
  662. '_matchingData' => [
  663. 'Tags' => [
  664. 'id' => 3,
  665. 'name' => 'tag3',
  666. ],
  667. 'ArticlesTags' => ['article_id' => 2, 'tag_id' => 3]
  668. ]
  669. ]
  670. ];
  671. $this->assertEquals($expected, $results);
  672. $query = new Query($this->connection, $table);
  673. $results = $query->select()
  674. ->matching('Tags', function ($q) {
  675. return $q->where(['Tags.name' => 'tag2']);
  676. })
  677. ->hydrate(false)
  678. ->toArray();
  679. $expected = [
  680. [
  681. 'id' => 1,
  682. 'title' => 'First Article',
  683. 'body' => 'First Article Body',
  684. 'author_id' => 1,
  685. 'published' => 'Y',
  686. '_matchingData' => [
  687. 'Tags' => [
  688. 'id' => 2,
  689. 'name' => 'tag2',
  690. ],
  691. 'ArticlesTags' => ['article_id' => 1, 'tag_id' => 2]
  692. ]
  693. ]
  694. ];
  695. $this->assertEquals($expected, $results);
  696. }
  697. /**
  698. * Tests that it is possible to filter by deep associations
  699. *
  700. * @return void
  701. */
  702. public function testMatchingDotNotation()
  703. {
  704. $query = new Query($this->connection, $this->table);
  705. $table = TableRegistry::get('authors');
  706. TableRegistry::get('articles');
  707. $table->hasMany('articles');
  708. TableRegistry::get('articles')->belongsToMany('tags');
  709. $results = $query->repository($table)
  710. ->select()
  711. ->hydrate(false)
  712. ->matching('articles.tags', function ($q) {
  713. return $q->where(['tags.id' => 2]);
  714. })
  715. ->toArray();
  716. $expected = [
  717. [
  718. 'id' => 1,
  719. 'name' => 'mariano',
  720. '_matchingData' => [
  721. 'tags' => [
  722. 'id' => 2,
  723. 'name' => 'tag2',
  724. ],
  725. 'articles' => [
  726. 'id' => 1,
  727. 'author_id' => 1,
  728. 'title' => 'First Article',
  729. 'body' => 'First Article Body',
  730. 'published' => 'Y'
  731. ],
  732. 'ArticlesTags' => [
  733. 'article_id' => 1,
  734. 'tag_id' => 2
  735. ]
  736. ]
  737. ]
  738. ];
  739. $this->assertEquals($expected, $results);
  740. }
  741. /**
  742. * Test setResult()
  743. *
  744. * @return void
  745. */
  746. public function testSetResult()
  747. {
  748. $query = new Query($this->connection, $this->table);
  749. $stmt = $this->getMock('Cake\Database\StatementInterface');
  750. $results = new ResultSet($query, $stmt);
  751. $query->setResult($results);
  752. $this->assertSame($results, $query->all());
  753. }
  754. /**
  755. * Tests that applying array options to a query will convert them
  756. * to equivalent function calls with the correspondent array values
  757. *
  758. * @return void
  759. */
  760. public function testApplyOptions()
  761. {
  762. $options = [
  763. 'fields' => ['field_a', 'field_b'],
  764. 'conditions' => ['field_a' => 1, 'field_b' => 'something'],
  765. 'limit' => 1,
  766. 'order' => ['a' => 'ASC'],
  767. 'offset' => 5,
  768. 'group' => ['field_a'],
  769. 'having' => ['field_a >' => 100],
  770. 'contain' => ['table_a' => ['table_b']],
  771. 'join' => ['table_a' => ['conditions' => ['a > b']]]
  772. ];
  773. $query = new Query($this->connection, $this->table);
  774. $query->applyOptions($options);
  775. $this->assertEquals(['field_a', 'field_b'], $query->clause('select'));
  776. $expected = new QueryExpression($options['conditions'], $this->fooTypeMap);
  777. $result = $query->clause('where');
  778. $this->assertEquals($expected, $result);
  779. $this->assertEquals(1, $query->clause('limit'));
  780. $expected = new QueryExpression(['a > b']);
  781. $expected->typeMap($this->fooTypeMap);
  782. $result = $query->clause('join');
  783. $this->assertEquals([
  784. 'table_a' => ['alias' => 'table_a', 'type' => 'INNER', 'conditions' => $expected]
  785. ], $result);
  786. $expected = new OrderByExpression(['a' => 'ASC']);
  787. $this->assertEquals($expected, $query->clause('order'));
  788. $this->assertEquals(5, $query->clause('offset'));
  789. $this->assertEquals(['field_a'], $query->clause('group'));
  790. $expected = new QueryExpression($options['having']);
  791. $expected->typeMap($this->fooTypeMap);
  792. $this->assertEquals($expected, $query->clause('having'));
  793. $expected = ['table_a' => ['table_b' => []]];
  794. $this->assertEquals($expected, $query->contain());
  795. }
  796. /**
  797. * Test that page is applied after limit.
  798. *
  799. * @return void
  800. */
  801. public function testApplyOptionsPageIsLast()
  802. {
  803. $query = new Query($this->connection, $this->table);
  804. $opts = [
  805. 'page' => 3,
  806. 'limit' => 5
  807. ];
  808. $query->applyOptions($opts);
  809. $this->assertEquals(5, $query->clause('limit'));
  810. $this->assertEquals(10, $query->clause('offset'));
  811. }
  812. /**
  813. * ApplyOptions should ignore null values.
  814. *
  815. * @return void
  816. */
  817. public function testApplyOptionsIgnoreNull()
  818. {
  819. $options = [
  820. 'fields' => null,
  821. ];
  822. $query = new Query($this->connection, $this->table);
  823. $query->applyOptions($options);
  824. $this->assertEquals([], $query->clause('select'));
  825. }
  826. /**
  827. * Tests getOptions() method
  828. *
  829. * @return void
  830. */
  831. public function testGetOptions()
  832. {
  833. $options = ['doABarrelRoll' => true, 'fields' => ['id', 'name']];
  834. $query = new Query($this->connection, $this->table);
  835. $query->applyOptions($options);
  836. $expected = ['doABarrelRoll' => true];
  837. $this->assertEquals($expected, $query->getOptions());
  838. $expected = ['doABarrelRoll' => false, 'doAwesome' => true];
  839. $query->applyOptions($expected);
  840. $this->assertEquals($expected, $query->getOptions());
  841. }
  842. /**
  843. * Tests registering mappers with mapReduce()
  844. *
  845. * @return void
  846. */
  847. public function testMapReduceOnlyMapper()
  848. {
  849. $mapper1 = function () {
  850. };
  851. $mapper2 = function () {
  852. };
  853. $query = new Query($this->connection, $this->table);
  854. $this->assertSame($query, $query->mapReduce($mapper1));
  855. $this->assertEquals(
  856. [['mapper' => $mapper1, 'reducer' => null]],
  857. $query->mapReduce()
  858. );
  859. $this->assertEquals($query, $query->mapReduce($mapper2));
  860. $result = $query->mapReduce();
  861. $this->assertSame(
  862. [
  863. ['mapper' => $mapper1, 'reducer' => null],
  864. ['mapper' => $mapper2, 'reducer' => null]
  865. ],
  866. $result
  867. );
  868. }
  869. /**
  870. * Tests registering mappers and reducers with mapReduce()
  871. *
  872. * @return void
  873. */
  874. public function testMapReduceBothMethods()
  875. {
  876. $mapper1 = function () {
  877. };
  878. $mapper2 = function () {
  879. };
  880. $reducer1 = function () {
  881. };
  882. $reducer2 = function () {
  883. };
  884. $query = new Query($this->connection, $this->table);
  885. $this->assertSame($query, $query->mapReduce($mapper1, $reducer1));
  886. $this->assertEquals(
  887. [['mapper' => $mapper1, 'reducer' => $reducer1]],
  888. $query->mapReduce()
  889. );
  890. $this->assertSame($query, $query->mapReduce($mapper2, $reducer2));
  891. $this->assertEquals(
  892. [
  893. ['mapper' => $mapper1, 'reducer' => $reducer1],
  894. ['mapper' => $mapper2, 'reducer' => $reducer2]
  895. ],
  896. $query->mapReduce()
  897. );
  898. }
  899. /**
  900. * Tests that it is possible to overwrite previous map reducers
  901. *
  902. * @return void
  903. */
  904. public function testOverwriteMapReduce()
  905. {
  906. $mapper1 = function () {
  907. };
  908. $mapper2 = function () {
  909. };
  910. $reducer1 = function () {
  911. };
  912. $reducer2 = function () {
  913. };
  914. $query = new Query($this->connection, $this->table);
  915. $this->assertEquals($query, $query->mapReduce($mapper1, $reducer1));
  916. $this->assertEquals(
  917. [['mapper' => $mapper1, 'reducer' => $reducer1]],
  918. $query->mapReduce()
  919. );
  920. $this->assertEquals($query, $query->mapReduce($mapper2, $reducer2, true));
  921. $this->assertEquals(
  922. [['mapper' => $mapper2, 'reducer' => $reducer2]],
  923. $query->mapReduce()
  924. );
  925. }
  926. /**
  927. * Tests that multiple map reducers can be stacked
  928. *
  929. * @return void
  930. */
  931. public function testResultsAreWrappedInMapReduce()
  932. {
  933. $params = [$this->connection, $this->table];
  934. $query = $this->getMock('\Cake\ORM\Query', ['execute'], $params);
  935. $statement = $this->getMock(
  936. '\Database\StatementInterface',
  937. ['fetch', 'closeCursor', 'rowCount']
  938. );
  939. $statement->expects($this->exactly(2))
  940. ->method('fetch')
  941. ->will($this->onConsecutiveCalls(['a' => 1], ['a' => 2]));
  942. $statement->expects($this->once())
  943. ->method('rowCount')
  944. ->will($this->returnValue(2));
  945. $query->expects($this->once())
  946. ->method('execute')
  947. ->will($this->returnValue($statement));
  948. $query->mapReduce(function ($v, $k, $mr) {
  949. $mr->emit($v['a']);
  950. });
  951. $query->mapReduce(
  952. function ($v, $k, $mr) {
  953. $mr->emitIntermediate($v, $k);
  954. },
  955. function ($v, $k, $mr) {
  956. $mr->emit($v[0] + 1);
  957. }
  958. );
  959. $this->assertEquals([2, 3], iterator_to_array($query->all()));
  960. }
  961. /**
  962. * Tests first() method when the query has not been executed before
  963. *
  964. * @return void
  965. */
  966. public function testFirstDirtyQuery()
  967. {
  968. $table = TableRegistry::get('articles', ['table' => 'articles']);
  969. $query = new Query($this->connection, $table);
  970. $result = $query->select(['id'])->hydrate(false)->first();
  971. $this->assertEquals(['id' => 1], $result);
  972. $this->assertEquals(1, $query->clause('limit'));
  973. $result = $query->select(['id'])->first();
  974. $this->assertEquals(['id' => 1], $result);
  975. }
  976. /**
  977. * Tests that first can be called again on an already executed query
  978. *
  979. * @return void
  980. */
  981. public function testFirstCleanQuery()
  982. {
  983. $table = TableRegistry::get('articles', ['table' => 'articles']);
  984. $query = new Query($this->connection, $table);
  985. $query->select(['id'])->toArray();
  986. $first = $query->hydrate(false)->first();
  987. $this->assertEquals(['id' => 1], $first);
  988. $this->assertEquals(1, $query->clause('limit'));
  989. }
  990. /**
  991. * Tests that first() will not execute the same query twice
  992. *
  993. * @return void
  994. */
  995. public function testFirstSameResult()
  996. {
  997. $table = TableRegistry::get('articles', ['table' => 'articles']);
  998. $query = new Query($this->connection, $table);
  999. $query->select(['id'])->toArray();
  1000. $first = $query->hydrate(false)->first();
  1001. $resultSet = $query->all();
  1002. $this->assertEquals(['id' => 1], $first);
  1003. $this->assertSame($resultSet, $query->all());
  1004. }
  1005. /**
  1006. * Tests that first can be called against a query with a mapReduce
  1007. *
  1008. * @return void
  1009. */
  1010. public function testFirstMapReduce()
  1011. {
  1012. $map = function ($row, $key, $mapReduce) {
  1013. $mapReduce->emitIntermediate($row['id'], 'id');
  1014. };
  1015. $reduce = function ($values, $key, $mapReduce) {
  1016. $mapReduce->emit(array_sum($values));
  1017. };
  1018. $table = TableRegistry::get('articles', ['table' => 'articles']);
  1019. $query = new Query($this->connection, $table);
  1020. $query->select(['id'])
  1021. ->hydrate(false)
  1022. ->mapReduce($map, $reduce);
  1023. $first = $query->first();
  1024. $this->assertEquals(1, $first);
  1025. }
  1026. /**
  1027. * Testing hydrating a result set into Entity objects
  1028. *
  1029. * @return void
  1030. */
  1031. public function testHydrateSimple()
  1032. {
  1033. $table = TableRegistry::get('articles', ['table' => 'articles']);
  1034. $query = new Query($this->connection, $table);
  1035. $results = $query->select()->toArray();
  1036. $this->assertCount(3, $results);
  1037. foreach ($results as $r) {
  1038. $this->assertInstanceOf('Cake\ORM\Entity', $r);
  1039. }
  1040. $first = $results[0];
  1041. $this->assertEquals(1, $first->id);
  1042. $this->assertEquals(1, $first->author_id);
  1043. $this->assertEquals('First Article', $first->title);
  1044. $this->assertEquals('First Article Body', $first->body);
  1045. $this->assertEquals('Y', $first->published);
  1046. }
  1047. /**
  1048. * Tests that has many results are also hydrated correctly
  1049. *
  1050. * @return void
  1051. */
  1052. public function testHydrateHasMany()
  1053. {
  1054. $table = TableRegistry::get('authors');
  1055. TableRegistry::get('articles');
  1056. $table->hasMany('articles', [
  1057. 'propertyName' => 'articles',
  1058. 'sort' => ['articles.id' => 'asc']
  1059. ]);
  1060. $query = new Query($this->connection, $table);
  1061. $results = $query->select()
  1062. ->contain('articles')
  1063. ->toArray();
  1064. $first = $results[0];
  1065. foreach ($first->articles as $r) {
  1066. $this->assertInstanceOf('Cake\ORM\Entity', $r);
  1067. }
  1068. $this->assertCount(2, $first->articles);
  1069. $expected = [
  1070. 'id' => 1,
  1071. 'title' => 'First Article',
  1072. 'body' => 'First Article Body',
  1073. 'author_id' => 1,
  1074. 'published' => 'Y',
  1075. ];
  1076. $this->assertEquals($expected, $first->articles[0]->toArray());
  1077. $expected = [
  1078. 'id' => 3,
  1079. 'title' => 'Third Article',
  1080. 'author_id' => 1,
  1081. 'body' => 'Third Article Body',
  1082. 'published' => 'Y',
  1083. ];
  1084. $this->assertEquals($expected, $first->articles[1]->toArray());
  1085. }
  1086. /**
  1087. * Tests that belongsToMany associations are also correctly hydrated
  1088. *
  1089. * @return void
  1090. */
  1091. public function testHydrateBelongsToMany()
  1092. {
  1093. $table = TableRegistry::get('Articles');
  1094. TableRegistry::get('Tags');
  1095. TableRegistry::get('ArticlesTags', [
  1096. 'table' => 'articles_tags'
  1097. ]);
  1098. $table->belongsToMany('Tags');
  1099. $query = new Query($this->connection, $table);
  1100. $results = $query
  1101. ->select()
  1102. ->contain('Tags')
  1103. ->toArray();
  1104. $first = $results[0];
  1105. foreach ($first->tags as $r) {
  1106. $this->assertInstanceOf('Cake\ORM\Entity', $r);
  1107. }
  1108. $this->assertCount(2, $first->tags);
  1109. $expected = [
  1110. 'id' => 1,
  1111. 'name' => 'tag1',
  1112. '_joinData' => ['article_id' => 1, 'tag_id' => 1]
  1113. ];
  1114. $this->assertEquals($expected, $first->tags[0]->toArray());
  1115. $expected = [
  1116. 'id' => 2,
  1117. 'name' => 'tag2',
  1118. '_joinData' => ['article_id' => 1, 'tag_id' => 2]
  1119. ];
  1120. $this->assertEquals($expected, $first->tags[1]->toArray());
  1121. }
  1122. /**
  1123. * Tests that belongsToMany associations are also correctly hydrated
  1124. *
  1125. * @return void
  1126. */
  1127. public function testFormatResultsBelongsToMany()
  1128. {
  1129. $table = TableRegistry::get('Articles');
  1130. TableRegistry::get('Tags');
  1131. $articlesTags = TableRegistry::get('ArticlesTags', [
  1132. 'table' => 'articles_tags'
  1133. ]);
  1134. $table->belongsToMany('Tags');
  1135. $articlesTags
  1136. ->eventManager()
  1137. ->attach(function ($event, $query) {
  1138. $query->formatResults(function ($results) {
  1139. return $results;
  1140. });
  1141. }, 'Model.beforeFind');
  1142. $query = new Query($this->connection, $table);
  1143. $results = $query
  1144. ->select()
  1145. ->contain('Tags')
  1146. ->toArray();
  1147. $first = $results[0];
  1148. foreach ($first->tags as $r) {
  1149. $this->assertInstanceOf('Cake\ORM\Entity', $r);
  1150. }
  1151. $this->assertCount(2, $first->tags);
  1152. $expected = [
  1153. 'id' => 1,
  1154. 'name' => 'tag1',
  1155. '_joinData' => ['article_id' => 1, 'tag_id' => 1]
  1156. ];
  1157. $this->assertEquals($expected, $first->tags[0]->toArray());
  1158. $expected = [
  1159. 'id' => 2,
  1160. 'name' => 'tag2',
  1161. '_joinData' => ['article_id' => 1, 'tag_id' => 2]
  1162. ];
  1163. $this->assertEquals($expected, $first->tags[1]->toArray());
  1164. }
  1165. /**
  1166. * Tests that belongsTo relations are correctly hydrated
  1167. *
  1168. * @dataProvider internalStategiesProvider
  1169. * @return void
  1170. */
  1171. public function testHydrateBelongsTo($strategy)
  1172. {
  1173. $table = TableRegistry::get('articles');
  1174. TableRegistry::get('authors');
  1175. $table->belongsTo('authors', ['strategy' => $strategy]);
  1176. $query = new Query($this->connection, $table);
  1177. $results = $query->select()
  1178. ->contain('authors')
  1179. ->order(['articles.id' => 'asc'])
  1180. ->toArray();
  1181. $this->assertCount(3, $results);
  1182. $first = $results[0];
  1183. $this->assertInstanceOf('Cake\ORM\Entity', $first->author);
  1184. $expected = ['id' => 1, 'name' => 'mariano'];
  1185. $this->assertEquals($expected, $first->author->toArray());
  1186. }
  1187. /**
  1188. * Tests that deeply nested associations are also hydrated correctly
  1189. *
  1190. * @dataProvider internalStategiesProvider
  1191. * @return void
  1192. */
  1193. public function testHydrateDeep($strategy)
  1194. {
  1195. $table = TableRegistry::get('authors');
  1196. $article = TableRegistry::get('articles');
  1197. $table->hasMany('articles', [
  1198. 'propertyName' => 'articles',
  1199. 'sort' => ['articles.id' => 'asc']
  1200. ]);
  1201. $article->belongsTo('authors', ['strategy' => $strategy]);
  1202. $query = new Query($this->connection, $table);
  1203. $results = $query->select()
  1204. ->contain(['articles' => ['authors']])
  1205. ->toArray();
  1206. $this->assertCount(4, $results);
  1207. $first = $results[0];
  1208. $this->assertInstanceOf('Cake\ORM\Entity', $first->articles[0]->author);
  1209. $expected = ['id' => 1, 'name' => 'mariano'];
  1210. $this->assertEquals($expected, $first->articles[0]->author->toArray());
  1211. $this->assertTrue(isset($results[3]->articles));
  1212. }
  1213. /**
  1214. * Tests that it is possible to use a custom entity class
  1215. *
  1216. * @return void
  1217. */
  1218. public function testHydrateCustomObject()
  1219. {
  1220. $class = $this->getMockClass('\Cake\ORM\Entity', ['fakeMethod']);
  1221. $table = TableRegistry::get('articles', [
  1222. 'table' => 'articles',
  1223. 'entityClass' => '\\' . $class
  1224. ]);
  1225. $query = new Query($this->connection, $table);
  1226. $results = $query->select()->toArray();
  1227. $this->assertCount(3, $results);
  1228. foreach ($results as $r) {
  1229. $this->assertInstanceOf($class, $r);
  1230. }
  1231. $first = $results[0];
  1232. $this->assertEquals(1, $first->id);
  1233. $this->assertEquals(1, $first->author_id);
  1234. $this->assertEquals('First Article', $first->title);
  1235. $this->assertEquals('First Article Body', $first->body);
  1236. $this->assertEquals('Y', $first->published);
  1237. }
  1238. /**
  1239. * Tests that has many results are also hydrated correctly
  1240. * when specified a custom entity class
  1241. *
  1242. * @return void
  1243. */
  1244. public function testHydrateHasManyCustomEntity()
  1245. {
  1246. $authorEntity = $this->getMockClass('\Cake\ORM\Entity', ['foo']);
  1247. $articleEntity = $this->getMockClass('\Cake\ORM\Entity', ['foo']);
  1248. $table = TableRegistry::get('authors', [
  1249. 'entityClass' => '\\' . $authorEntity
  1250. ]);
  1251. TableRegistry::get('articles', [
  1252. 'entityClass' => '\\' . $articleEntity
  1253. ]);
  1254. $table->hasMany('articles', [
  1255. 'propertyName' => 'articles',
  1256. 'sort' => ['articles.id' => 'asc']
  1257. ]);
  1258. $query = new Query($this->connection, $table);
  1259. $results = $query->select()
  1260. ->contain('articles')
  1261. ->toArray();
  1262. $first = $results[0];
  1263. $this->assertInstanceOf($authorEntity, $first);
  1264. foreach ($first->articles as $r) {
  1265. $this->assertInstanceOf($articleEntity, $r);
  1266. }
  1267. $this->assertCount(2, $first->articles);
  1268. $expected = [
  1269. 'id' => 1,
  1270. 'title' => 'First Article',
  1271. 'body' => 'First Article Body',
  1272. 'author_id' => 1,
  1273. 'published' => 'Y',
  1274. ];
  1275. $this->assertEquals($expected, $first->articles[0]->toArray());
  1276. }
  1277. /**
  1278. * Tests that belongsTo relations are correctly hydrated into a custom entity class
  1279. *
  1280. * @return void
  1281. */
  1282. public function testHydrateBelongsToCustomEntity()
  1283. {
  1284. $authorEntity = $this->getMockClass('\Cake\ORM\Entity', ['foo']);
  1285. $table = TableRegistry::get('articles');
  1286. TableRegistry::get('authors', [
  1287. 'entityClass' => '\\' . $authorEntity
  1288. ]);
  1289. $table->belongsTo('authors');
  1290. $query = new Query($this->connection, $table);
  1291. $results = $query->select()
  1292. ->contain('authors')
  1293. ->order(['articles.id' => 'asc'])
  1294. ->toArray();
  1295. $first = $results[0];
  1296. $this->assertInstanceOf($authorEntity, $first->author);
  1297. }
  1298. /**
  1299. * Test getting counts from queries.
  1300. *
  1301. * @return void
  1302. */
  1303. public function testCount()
  1304. {
  1305. $table = TableRegistry::get('articles');
  1306. $result = $table->find('all')->count();
  1307. $this->assertSame(3, $result);
  1308. $query = $table->find('all')
  1309. ->where(['id >' => 1])
  1310. ->limit(1);
  1311. $result = $query->count();
  1312. $this->assertSame(2, $result);
  1313. $result = $query->all();
  1314. $this->assertCount(1, $result);
  1315. $this->assertEquals(2, $result->first()->id);
  1316. }
  1317. /**
  1318. * test count with a beforeFind.
  1319. *
  1320. * @return void
  1321. */
  1322. public function testCountBeforeFind()
  1323. {
  1324. $table = TableRegistry::get('Articles');
  1325. $table->hasMany('Comments');
  1326. $table->eventManager()
  1327. ->attach(function ($event, $query) {
  1328. $query
  1329. ->limit(1)
  1330. ->order(['Articles.title' => 'DESC']);
  1331. }, 'Model.beforeFind');
  1332. $query = $table->find();
  1333. $result = $query->count();
  1334. $this->assertSame(3, $result);
  1335. }
  1336. /**
  1337. * Test that count() returns correct results with group by.
  1338. *
  1339. * @return void
  1340. */
  1341. public function testCountWithGroup()
  1342. {
  1343. $table = TableRegistry::get('articles');
  1344. $query = $table->find('all');
  1345. $query->select(['author_id', 's' => $query->func()->sum('id')])
  1346. ->group(['author_id']);
  1347. $result = $query->count();
  1348. $this->assertEquals(2, $result);
  1349. }
  1350. /**
  1351. * Tests that it is possible to provide a callback for calculating the count
  1352. * of a query
  1353. *
  1354. * @return void
  1355. */
  1356. public function testCountWithCustomCounter()
  1357. {
  1358. $table = TableRegistry::get('articles');
  1359. $query = $table->find('all');
  1360. $query
  1361. ->select(['author_id', 's' => $query->func()->sum('id')])
  1362. ->where(['id >' => 2])
  1363. ->group(['author_id'])
  1364. ->counter(function ($q) use ($query) {
  1365. $this->assertNotSame($q, $query);
  1366. return $q->select([], true)->group([], true)->count();
  1367. });
  1368. $result = $query->count();
  1369. $this->assertEquals(1, $result);
  1370. }
  1371. /**
  1372. * Test update method.
  1373. *
  1374. * @return void
  1375. */
  1376. public function testUpdate()
  1377. {
  1378. $table = TableRegistry::get('articles');
  1379. $result = $table->query()
  1380. ->update()
  1381. ->set(['title' => 'First'])
  1382. ->execute();
  1383. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  1384. $this->assertTrue($result->rowCount() > 0);
  1385. }
  1386. /**
  1387. * Test insert method.
  1388. *
  1389. * @return void
  1390. */
  1391. public function testInsert()
  1392. {
  1393. $table = TableRegistry::get('articles');
  1394. $result = $table->query()
  1395. ->insert(['title'])
  1396. ->values(['title' => 'First'])
  1397. ->values(['title' => 'Second'])
  1398. ->execute();
  1399. $result->closeCursor();
  1400. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  1401. //PDO_SQLSRV returns -1 for successful inserts when using INSERT ... OUTPUT
  1402. if (!$this->connection->driver() instanceof \Cake\Database\Driver\Sqlserver) {
  1403. $this->assertEquals(2, $result->rowCount());
  1404. } else {
  1405. $this->assertEquals(-1, $result->rowCount());
  1406. }
  1407. }
  1408. /**
  1409. * Test delete method.
  1410. *
  1411. * @return void
  1412. */
  1413. public function testDelete()
  1414. {
  1415. $table = TableRegistry::get('articles');
  1416. $result = $table->query()
  1417. ->delete()
  1418. ->where(['id >=' => 1])
  1419. ->execute();
  1420. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  1421. $this->assertTrue($result->rowCount() > 0);
  1422. }
  1423. /**
  1424. * Provides a list of collection methods that can be proxied
  1425. * from the query
  1426. *
  1427. * @return array
  1428. */
  1429. public function collectionMethodsProvider()
  1430. {
  1431. $identity = function ($a) {
  1432. return $a;
  1433. };
  1434. return [
  1435. ['filter', $identity],
  1436. ['reject', $identity],
  1437. ['every', $identity],
  1438. ['some', $identity],
  1439. ['contains', $identity],
  1440. ['map', $identity],
  1441. ['reduce', $identity],
  1442. ['extract', $identity],
  1443. ['max', $identity],
  1444. ['min', $identity],
  1445. ['sortBy', $identity],
  1446. ['groupBy', $identity],
  1447. ['countBy', $identity],
  1448. ['shuffle', $identity],
  1449. ['sample', $identity],
  1450. ['take', 1],
  1451. ['append', new \ArrayIterator],
  1452. ['compile', 1],
  1453. ];
  1454. }
  1455. /**
  1456. * Tests that query can proxy collection methods
  1457. *
  1458. * @dataProvider collectionMethodsProvider
  1459. * @return void
  1460. */
  1461. public function testCollectionProxy($method, $arg)
  1462. {
  1463. $query = $this->getMock(
  1464. '\Cake\ORM\Query',
  1465. ['all'],
  1466. [$this->connection, $this->table]
  1467. );
  1468. $query->select();
  1469. $resultSet = $this->getMock('\Cake\ORM\ResultSet', [], [$query, null]);
  1470. $query->expects($this->once())
  1471. ->method('all')
  1472. ->will($this->returnValue($resultSet));
  1473. $resultSet->expects($this->once())
  1474. ->method($method)
  1475. ->with($arg, 'extra')
  1476. ->will($this->returnValue(new \Cake\Collection\Collection([])));
  1477. $this->assertInstanceOf(
  1478. '\Cake\Collection\Collection',
  1479. $query->{$method}($arg, 'extra')
  1480. );
  1481. }
  1482. /**
  1483. * Tests that calling an inexistent method in query throws an
  1484. * exception
  1485. *
  1486. * @expectedException \BadMethodCallException
  1487. * @expectedExceptionMessage Unknown method "derpFilter"
  1488. * @return void
  1489. */
  1490. public function testCollectionProxyBadMethod()
  1491. {
  1492. TableRegistry::get('articles')->find('all')->derpFilter();
  1493. }
  1494. /**
  1495. * cache() should fail on non select queries.
  1496. *
  1497. * @expectedException \RuntimeException
  1498. * @return void
  1499. */
  1500. public function testCacheErrorOnNonSelect()
  1501. {
  1502. $table = TableRegistry::get('articles', ['table' => 'articles']);
  1503. $query = new Query($this->connection, $table);
  1504. $query->insert(['test']);
  1505. $query->cache('my_key');
  1506. }
  1507. /**
  1508. * Integration test for query caching.
  1509. *
  1510. * @return void
  1511. */
  1512. public function testCacheReadIntegration()
  1513. {
  1514. $query = $this->getMock(
  1515. '\Cake\ORM\Query',
  1516. ['execute'],
  1517. [$this->connection, $this->table]
  1518. );
  1519. $resultSet = $this->getMock('\Cake\ORM\ResultSet', [], [$query, null]);
  1520. $query->expects($this->never())
  1521. ->method('execute');
  1522. $cacher = $this->getMock('Cake\Cache\CacheEngine');
  1523. $cacher->expects($this->once())
  1524. ->method('read')
  1525. ->with('my_key')
  1526. ->will($this->returnValue($resultSet));
  1527. $query->cache('my_key', $cacher)
  1528. ->where(['id' => 1]);
  1529. $results = $query->all();
  1530. $this->assertSame($resultSet, $results);
  1531. }
  1532. /**
  1533. * Integration test for query caching.
  1534. *
  1535. * @return void
  1536. */
  1537. public function testCacheWriteIntegration()
  1538. {
  1539. $table = TableRegistry::get('Articles');
  1540. $query = new Query($this->connection, $table);
  1541. $query->select(['id', 'title']);
  1542. $cacher = $this->getMock('Cake\Cache\CacheEngine');
  1543. $cacher->expects($this->once())
  1544. ->method('write')
  1545. ->with(
  1546. 'my_key',
  1547. $this->isInstanceOf('Cake\Datasource\ResultSetInterface')
  1548. );
  1549. $query->cache('my_key', $cacher)
  1550. ->where(['id' => 1]);
  1551. $query->all();
  1552. }
  1553. /**
  1554. * Integration test to show filtering associations using contain and a closure
  1555. *
  1556. * @return void
  1557. */
  1558. public function testContainWithClosure()
  1559. {
  1560. $table = TableRegistry::get('authors');
  1561. $table->hasMany('articles');
  1562. $query = new Query($this->connection, $table);
  1563. $query
  1564. ->select()
  1565. ->contain(['articles' => function ($q) {
  1566. return $q->where(['articles.id' => 1]);
  1567. }]);
  1568. $ids = [];
  1569. foreach ($query as $entity) {
  1570. foreach ((array)$entity->articles as $article) {
  1571. $ids[] = $article->id;
  1572. }
  1573. }
  1574. $this->assertEquals([1], array_unique($ids));
  1575. }
  1576. /**
  1577. * Integration test to ensure that filtering associations with the queryBuilder
  1578. * option works.
  1579. *
  1580. * @expectedException \RuntimeException
  1581. * @return void
  1582. */
  1583. public function testContainWithQueryBuilderHasManyError()
  1584. {
  1585. $table = TableRegistry::get('Authors');
  1586. $table->hasMany('Articles');
  1587. $query = new Query($this->connection, $table);
  1588. $query->select()
  1589. ->contain([
  1590. 'Articles' => [
  1591. 'foreignKey' => false,
  1592. 'queryBuilder' => function ($q) {
  1593. return $q->where(['articles.id' => 1]);
  1594. }
  1595. ]
  1596. ]);
  1597. $query->toArray();
  1598. }
  1599. /**
  1600. * Integration test to ensure that filtering associations with the queryBuilder
  1601. * option works.
  1602. *
  1603. * @return void
  1604. */
  1605. public function testContainWithQueryBuilderJoinableAssociation()
  1606. {
  1607. $table = TableRegistry::get('Authors');
  1608. $table->hasOne('Articles');
  1609. $query = new Query($this->connection, $table);
  1610. $query->select()
  1611. ->contain([
  1612. 'Articles' => [
  1613. 'foreignKey' => false,
  1614. 'queryBuilder' => function ($q) {
  1615. return $q->where(['Articles.id' => 1]);
  1616. }
  1617. ]
  1618. ]);
  1619. $result = $query->toArray();
  1620. $this->assertEquals(1, $result[0]->article->id);
  1621. $this->assertEquals(1, $result[1]->article->id);
  1622. $articles = TableRegistry::get('Articles');
  1623. $articles->belongsTo('Authors');
  1624. $query = new Query($this->connection, $articles);
  1625. $query->select()
  1626. ->contain([
  1627. 'Authors' => [
  1628. 'foreignKey' => false,
  1629. 'queryBuilder' => function ($q) {
  1630. return $q->where(['Authors.id' => 1]);
  1631. }
  1632. ]
  1633. ]);
  1634. $result = $query->toArray();
  1635. $this->assertEquals(1, $result[0]->author->id);
  1636. }
  1637. /**
  1638. * Tests the formatResults method
  1639. *
  1640. * @return void
  1641. */
  1642. public function testFormatResults()
  1643. {
  1644. $callback1 = function () {
  1645. };
  1646. $callback2 = function () {
  1647. };
  1648. $table = TableRegistry::get('authors');
  1649. $query = new Query($this->connection, $table);
  1650. $this->assertSame($query, $query->formatResults($callback1));
  1651. $this->assertSame([$callback1], $query->formatResults());
  1652. $this->assertSame($query, $query->formatResults($callback2));
  1653. $this->assertSame([$callback1, $callback2], $query->formatResults());
  1654. $query->formatResults($callback2, true);
  1655. $this->assertSame([$callback2], $query->formatResults());
  1656. $query->formatResults(null, true);
  1657. $this->assertSame([], $query->formatResults());
  1658. $query->formatResults($callback1);
  1659. $query->formatResults($callback2, $query::PREPEND);
  1660. $this->assertSame([$callback2, $callback1], $query->formatResults());
  1661. }
  1662. /**
  1663. * Test fetching results from a qurey with a custom formatter
  1664. *
  1665. * @return void
  1666. */
  1667. public function testQueryWithFormatter()
  1668. {
  1669. $table = TableRegistry::get('authors');
  1670. $query = new Query($this->connection, $table);
  1671. $query->select()->formatResults(function ($results) {
  1672. $this->assertInstanceOf('Cake\ORM\ResultSet', $results);
  1673. return $results->indexBy('id');
  1674. });
  1675. $this->assertEquals([1, 2, 3, 4], array_keys($query->toArray()));
  1676. }
  1677. /**
  1678. * Test fetching results from a qurey with a two custom formatters
  1679. *
  1680. * @return void
  1681. */
  1682. public function testQueryWithStackedFormatters()
  1683. {
  1684. $table = TableRegistry::get('authors');
  1685. $query = new Query($this->connection, $table);
  1686. $query->select()->formatResults(function ($results) {
  1687. $this->assertInstanceOf('Cake\ORM\ResultSet', $results);
  1688. return $results->indexBy('id');
  1689. });
  1690. $query->formatResults(function ($results) {
  1691. return $results->extract('name');
  1692. });
  1693. $expected = [
  1694. 1 => 'mariano',
  1695. 2 => 'nate',
  1696. 3 => 'larry',
  1697. 4 => 'garrett'
  1698. ];
  1699. $this->assertEquals($expected, $query->toArray());
  1700. }
  1701. /**
  1702. * Tests that getting results from a query having a contained association
  1703. * will no attach joins twice if count() is called on it afterwards
  1704. *
  1705. * @return void
  1706. */
  1707. public function testCountWithContainCallingAll()
  1708. {
  1709. $table = TableRegistry::get('articles');
  1710. $table->belongsTo('authors');
  1711. $query = $table->find()
  1712. ->select(['id', 'title'])
  1713. ->contain('authors')
  1714. ->limit(2);
  1715. $results = $query->all();
  1716. $this->assertCount(2, $results);
  1717. $this->assertEquals(3, $query->count());
  1718. }
  1719. /**
  1720. * Tests that it is possible to apply formatters inside the query builder
  1721. * for belongsTo associations
  1722. *
  1723. * @return void
  1724. */
  1725. public function testFormatBelongsToRecords()
  1726. {
  1727. $table = TableRegistry::get('articles');
  1728. $table->belongsTo('authors');
  1729. $query = $table->find()
  1730. ->contain(['authors' => function ($q) {
  1731. return $q
  1732. ->formatResults(function ($authors) {
  1733. return $authors->map(function ($author) {
  1734. $author->idCopy = $author->id;
  1735. return $author;
  1736. });
  1737. })
  1738. ->formatResults(function ($authors) {
  1739. return $authors->map(function ($author) {
  1740. $author->idCopy = $author->idCopy + 2;
  1741. return $author;
  1742. });
  1743. });
  1744. }]);
  1745. $query->formatResults(function ($results) {
  1746. return $results->combine('id', 'author.idCopy');
  1747. });
  1748. $results = $query->toArray();
  1749. $expected = [1 => 3, 2 => 5, 3 => 3];
  1750. $this->assertEquals($expected, $results);
  1751. }
  1752. /**
  1753. * Tests it is possible to apply formatters to deep relations.
  1754. *
  1755. * @return void
  1756. */
  1757. public function testFormatDeepAssocationRecords()
  1758. {
  1759. $table = TableRegistry::get('ArticlesTags');
  1760. $table->belongsTo('Articles');
  1761. $table->association('Articles')->target()->belongsTo('Authors');
  1762. $builder = function ($q) {
  1763. return $q
  1764. ->formatResults(function ($results) {
  1765. return $results->map(function ($result) {
  1766. $result->idCopy = $result->id;
  1767. return $result;
  1768. });
  1769. })
  1770. ->formatResults(function ($results) {
  1771. return $results->map(function ($result) {
  1772. $result->idCopy = $result->idCopy + 2;
  1773. return $result;
  1774. });
  1775. });
  1776. };
  1777. $query = $table->find()
  1778. ->contain(['Articles' => $builder, 'Articles.Authors' => $builder])
  1779. ->order(['Articles.id' => 'ASC']);
  1780. $query->formatResults(function ($results) {
  1781. return $results->map(function ($row) {
  1782. return sprintf(
  1783. '%s - %s - %s',
  1784. $row->tag_id,
  1785. $row->article->idCopy,
  1786. $row->article->author->idCopy
  1787. );
  1788. });
  1789. });
  1790. $expected = ['1 - 3 - 3', '2 - 3 - 3', '1 - 4 - 5', '3 - 4 - 5'];
  1791. $this->assertEquals($expected, $query->toArray());
  1792. }
  1793. /**
  1794. * Tests that formatters cna be applied to deep associations that are fetched using
  1795. * additional queries
  1796. *
  1797. * @return void
  1798. */
  1799. public function testFormatDeepDistantAssociationRecords()
  1800. {
  1801. $table = TableRegistry::get('authors');
  1802. $table->hasMany('articles');
  1803. $articles = $table->association('articles')->target();
  1804. $articles->hasMany('articlesTags');
  1805. $articles->association('articlesTags')->target()->belongsTo('tags');
  1806. $query = $table->find()->contain(['articles.articlesTags.tags' => function ($q) {
  1807. return $q->formatResults(function ($results) {
  1808. return $results->map(function ($tag) {
  1809. $tag->name .= ' - visited';
  1810. return $tag;
  1811. });
  1812. });
  1813. }]);
  1814. $query->mapReduce(function ($row, $key, $mr) {
  1815. foreach ((array)$row->articles as $article) {
  1816. foreach ((array)$article->articles_tags as $articleTag) {
  1817. $mr->emit($articleTag->tag->name);
  1818. }
  1819. }
  1820. });
  1821. $expected = ['tag1 - visited', 'tag2 - visited', 'tag1 - visited', 'tag3 - visited'];
  1822. $this->assertEquals($expected, $query->toArray());
  1823. }
  1824. /**
  1825. * Tests that custom finders are applied to associations when using the proxies
  1826. *
  1827. * @return void
  1828. */
  1829. public function testCustomFinderInBelongsTo()
  1830. {
  1831. $table = TableRegistry::get('ArticlesTags');
  1832. $table->belongsTo('Articles', [
  1833. 'className' => 'TestApp\Model\Table\ArticlesTable',
  1834. 'finder' => 'published'
  1835. ]);
  1836. $result = $table->find()->contain('Articles');
  1837. $this->assertCount(4, $result->extract('article')->filter()->toArray());
  1838. $table->Articles->updateAll(['published' => 'N'], ['1 = 1']);
  1839. $result = $table->find()->contain('Articles');
  1840. $this->assertCount(0, $result->extract('article')->filter()->toArray());
  1841. }
  1842. /**
  1843. * Tests that it is possible to attach more association when using a query
  1844. * builder for other associations
  1845. *
  1846. * @return void
  1847. */
  1848. public function testContainInAssociationQuery()
  1849. {
  1850. $table = TableRegistry::get('ArticlesTags');
  1851. $table->belongsTo('Articles');
  1852. $table->association('Articles')->target()->belongsTo('Authors');
  1853. $query = $table->find()
  1854. ->order(['Articles.id' => 'ASC'])
  1855. ->contain(['Articles' => function ($q) {
  1856. return $q->contain('Authors');
  1857. }]);
  1858. $results = $query->extract('article.author.name')->toArray();
  1859. $expected = ['mariano', 'mariano', 'larry', 'larry'];
  1860. $this->assertEquals($expected, $results);
  1861. }
  1862. /**
  1863. * Tests that it is possible to apply more `matching` conditions inside query
  1864. * builders for associations
  1865. *
  1866. * @return void
  1867. */
  1868. public function testContainInAssociationMatching()
  1869. {
  1870. $table = TableRegistry::get('authors');
  1871. $table->hasMany('articles');
  1872. $articles = $table->association('articles')->target();
  1873. $articles->hasMany('articlesTags');
  1874. $articles->association('articlesTags')->target()->belongsTo('tags');
  1875. $query = $table->find()->matching('articles.articlesTags', function ($q) {
  1876. return $q->matching('tags', function ($q) {
  1877. return $q->where(['tags.name' => 'tag3']);
  1878. });
  1879. });
  1880. $results = $query->toArray();
  1881. $this->assertCount(1, $results);
  1882. $this->assertEquals('tag3', $results[0]->_matchingData['tags']->name);
  1883. }
  1884. /**
  1885. * Tests __debugInfo
  1886. *
  1887. * @return void
  1888. */
  1889. public function testDebugInfo()
  1890. {
  1891. $table = TableRegistry::get('authors');
  1892. $table->hasMany('articles');
  1893. $query = $table->find()
  1894. ->where(['id > ' => 1])
  1895. ->bufferResults(false)
  1896. ->hydrate(false)
  1897. ->matching('articles')
  1898. ->applyOptions(['foo' => 'bar'])
  1899. ->formatResults(function ($results) {
  1900. return $results;
  1901. })
  1902. ->mapReduce(function ($item, $key, $mr) {
  1903. $mr->emit($item);
  1904. });
  1905. $expected = [
  1906. 'sql' => $query->sql(),
  1907. 'params' => $query->valueBinder()->bindings(),
  1908. 'defaultTypes' => [
  1909. 'authors.id' => 'integer',
  1910. 'id' => 'integer',
  1911. 'authors.name' => 'string',
  1912. 'name' => 'string'
  1913. ],
  1914. 'decorators' => 0,
  1915. 'executed' => false,
  1916. 'hydrate' => false,
  1917. 'buffered' => false,
  1918. 'formatters' => 1,
  1919. 'mapReducers' => 1,
  1920. 'contain' => [],
  1921. 'matching' => [
  1922. 'articles' => [
  1923. 'queryBuilder' => null,
  1924. 'matching' => true
  1925. ]
  1926. ],
  1927. 'extraOptions' => ['foo' => 'bar'],
  1928. 'repository' => $table
  1929. ];
  1930. $this->assertSame($expected, $query->__debugInfo());
  1931. }
  1932. /**
  1933. * Tests that the eagerLoaded function works and is transmitted correctly to eagerly
  1934. * loaded associations
  1935. *
  1936. * @return void
  1937. */
  1938. public function testEagerLoaded()
  1939. {
  1940. $table = TableRegistry::get('authors');
  1941. $table->hasMany('articles');
  1942. $query = $table->find()->contain(['articles' => function ($q) {
  1943. $this->assertTrue($q->eagerLoaded());
  1944. return $q;
  1945. }]);
  1946. $this->assertFalse($query->eagerLoaded());
  1947. $table->eventManager()->attach(function ($e, $q, $o, $primary) {
  1948. $this->assertTrue($primary);
  1949. }, 'Model.beforeFind');
  1950. TableRegistry::get('articles')
  1951. ->eventManager()->attach(function ($e, $q, $o, $primary) {
  1952. $this->assertFalse($primary);
  1953. }, 'Model.beforeFind');
  1954. $query->all();
  1955. }
  1956. /**
  1957. * Tests that columns from manual joins are also contained in the result set
  1958. *
  1959. * @return void
  1960. */
  1961. public function testColumnsFromJoin()
  1962. {
  1963. $table = TableRegistry::get('articles');
  1964. $results = $table->find()
  1965. ->select(['title', 'person.name'])
  1966. ->join([
  1967. 'person' => [
  1968. 'table' => 'authors',
  1969. 'conditions' => ['person.id = articles.author_id']
  1970. ]
  1971. ])
  1972. ->order(['articles.id' => 'ASC'])
  1973. ->hydrate(false)
  1974. ->toArray();
  1975. $expected = [
  1976. ['title' => 'First Article', 'person' => ['name' => 'mariano']],
  1977. ['title' => 'Second Article', 'person' => ['name' => 'larry']],
  1978. ['title' => 'Third Article', 'person' => ['name' => 'mariano']],
  1979. ];
  1980. $this->assertSame($expected, $results);
  1981. }
  1982. /**
  1983. * Tests that it is possible to use the same association aliases in the association
  1984. * chain for contain
  1985. *
  1986. * @dataProvider internalStategiesProvider
  1987. * @return void
  1988. */
  1989. public function testRepeatedAssociationAliases($strategy)
  1990. {
  1991. $table = TableRegistry::get('ArticlesTags');
  1992. $table->belongsTo('Articles', ['strategy' => $strategy]);
  1993. $table->belongsTo('Tags', ['strategy' => $strategy]);
  1994. TableRegistry::get('Tags')->belongsToMany('Articles');
  1995. $results = $table
  1996. ->find()
  1997. ->contain(['Articles', 'Tags.Articles'])
  1998. ->hydrate(false)
  1999. ->toArray();
  2000. $this->assertNotEmpty($results[0]['tag']['articles']);
  2001. $this->assertNotEmpty($results[0]['article']);
  2002. $this->assertNotEmpty($results[1]['tag']['articles']);
  2003. $this->assertNotEmpty($results[1]['article']);
  2004. $this->assertNotEmpty($results[2]['tag']['articles']);
  2005. $this->assertNotEmpty($results[2]['article']);
  2006. }
  2007. /**
  2008. * Tests that a hasOne association using the select strategy will still have the
  2009. * key present in the results when no match is found
  2010. *
  2011. * @return void
  2012. */
  2013. public function testAssociationKeyPresent()
  2014. {
  2015. $table = TableRegistry::get('Articles');
  2016. $table->hasOne('ArticlesTags', ['strategy' => 'select']);
  2017. $article = $table->find()->where(['id' => 3])
  2018. ->hydrate(false)
  2019. ->contain('ArticlesTags')
  2020. ->first();
  2021. $this->assertNull($article['articles_tag']);
  2022. }
  2023. /**
  2024. * Tests that queries can be serialized to JSON to get the results
  2025. *
  2026. * @return void
  2027. */
  2028. public function testJsonSerialize()
  2029. {
  2030. $table = TableRegistry::get('Articles');
  2031. $this->assertEquals(
  2032. json_encode($table->find()),
  2033. json_encode($table->find()->toArray())
  2034. );
  2035. }
  2036. /**
  2037. * Test that addFields() works in the basic case.
  2038. *
  2039. * @return void
  2040. */
  2041. public function testAutoFields()
  2042. {
  2043. $table = TableRegistry::get('Articles');
  2044. $result = $table->find('all')
  2045. ->select(['myField' => '(SELECT 20)'])
  2046. ->autoFields(true)
  2047. ->hydrate(false)
  2048. ->first();
  2049. $this->assertArrayHasKey('myField', $result);
  2050. $this->assertArrayHasKey('id', $result);
  2051. $this->assertArrayHasKey('title', $result);
  2052. }
  2053. /**
  2054. * Test autoFields with auto fields.
  2055. *
  2056. * @return void
  2057. */
  2058. public function testAutoFieldsWithAssociations()
  2059. {
  2060. $table = TableRegistry::get('Articles');
  2061. $table->belongsTo('Authors');
  2062. $result = $table->find()
  2063. ->select(['myField' => '(SELECT 2 + 2)'])
  2064. ->autoFields(true)
  2065. ->hydrate(false)
  2066. ->contain('Authors')
  2067. ->first();
  2068. $this->assertArrayHasKey('myField', $result);
  2069. $this->assertArrayHasKey('title', $result);
  2070. $this->assertArrayHasKey('author', $result);
  2071. $this->assertNotNull($result['author']);
  2072. $this->assertArrayHasKey('name', $result['author']);
  2073. }
  2074. /**
  2075. * Test autoFields in contain query builder
  2076. *
  2077. * @return void
  2078. */
  2079. public function testAutoFieldsWithContainQueryBuilder()
  2080. {
  2081. $table = TableRegistry::get('Articles');
  2082. $table->belongsTo('Authors');
  2083. $result = $table->find()
  2084. ->select(['myField' => '(SELECT 2 + 2)'])
  2085. ->autoFields(true)
  2086. ->hydrate(false)
  2087. ->contain(['Authors' => function ($q) {
  2088. return $q->select(['compute' => '(SELECT 2 + 20)'])
  2089. ->autoFields(true);
  2090. }])
  2091. ->first();
  2092. $this->assertArrayHasKey('myField', $result);
  2093. $this->assertArrayHasKey('title', $result);
  2094. $this->assertArrayHasKey('author', $result);
  2095. $this->assertNotNull($result['author']);
  2096. $this->assertArrayHasKey('name', $result['author']);
  2097. $this->assertArrayHasKey('compute', $result);
  2098. }
  2099. /**
  2100. * Test that autofields works with count()
  2101. *
  2102. * @return void
  2103. */
  2104. public function testAutoFieldsCount()
  2105. {
  2106. $table = TableRegistry::get('Articles');
  2107. $result = $table->find()
  2108. ->select(['myField' => '(SELECT (2 + 2))'])
  2109. ->autoFields(true)
  2110. ->count();
  2111. $this->assertEquals(3, $result);
  2112. }
  2113. /**
  2114. * test that cleanCopy makes a cleaned up clone.
  2115. *
  2116. * @return void
  2117. */
  2118. public function testCleanCopy()
  2119. {
  2120. $table = TableRegistry::get('Articles');
  2121. $table->hasMany('Comments');
  2122. $query = $table->find();
  2123. $query->offset(10)
  2124. ->limit(1)
  2125. ->order(['Articles.id' => 'DESC'])
  2126. ->contain(['Comments']);
  2127. $copy = $query->cleanCopy();
  2128. $this->assertNotSame($copy, $query);
  2129. $this->assertNull($copy->clause('offset'));
  2130. $this->assertNull($copy->clause('limit'));
  2131. $this->assertNull($copy->clause('order'));
  2132. }
  2133. /**
  2134. * test that cleanCopy makes a cleaned up clone with a beforeFind.
  2135. *
  2136. * @return void
  2137. */
  2138. public function testCleanCopyBeforeFind()
  2139. {
  2140. $table = TableRegistry::get('Articles');
  2141. $table->hasMany('Comments');
  2142. $table->eventManager()
  2143. ->attach(function ($event, $query) {
  2144. $query
  2145. ->limit(5)
  2146. ->order(['Articles.title' => 'DESC']);
  2147. }, 'Model.beforeFind');
  2148. $query = $table->find();
  2149. $query->offset(10)
  2150. ->limit(1)
  2151. ->order(['Articles.id' => 'DESC'])
  2152. ->contain(['Comments']);
  2153. $copy = $query->cleanCopy();
  2154. $this->assertNotSame($copy, $query);
  2155. $this->assertNull($copy->clause('offset'));
  2156. $this->assertNull($copy->clause('limit'));
  2157. $this->assertNull($copy->clause('order'));
  2158. }
  2159. /**
  2160. * Test that finder options sent through via contain are sent to custom finder.
  2161. *
  2162. * @return void
  2163. */
  2164. public function testContainFinderCanSpecifyOptions()
  2165. {
  2166. $table = TableRegistry::get('Articles');
  2167. $table->belongsTo(
  2168. 'Authors',
  2169. ['className' => 'TestApp\Model\Table\AuthorsTable']
  2170. );
  2171. $authorId = 1;
  2172. $resultWithoutAuthor = $table->find('all')
  2173. ->where(['Articles.author_id' => $authorId])
  2174. ->contain([
  2175. 'Authors' => [
  2176. 'finder' => ['byAuthor' => ['author_id' => 2]]
  2177. ]
  2178. ]);
  2179. $resultWithAuthor = $table->find('all')
  2180. ->where(['Articles.author_id' => $authorId])
  2181. ->contain([
  2182. 'Authors' => [
  2183. 'finder' => ['byAuthor' => ['author_id' => $authorId]]
  2184. ]
  2185. ]);
  2186. $this->assertEmpty($resultWithoutAuthor->first()['author']);
  2187. $this->assertEquals($authorId, $resultWithAuthor->first()['author']['id']);
  2188. }
  2189. /**
  2190. * Tests that it is possible to bind arguments to a query and it will return the right
  2191. * results
  2192. *
  2193. * @return void
  2194. */
  2195. public function testCustomBindings()
  2196. {
  2197. $table = TableRegistry::get('Articles');
  2198. $query = $table->find()->where(['id >' => 1]);
  2199. $query->where(function ($exp) {
  2200. return $exp->add('author_id = :author');
  2201. });
  2202. $query->bind(':author', 1, 'integer');
  2203. $this->assertEquals(1, $query->count());
  2204. $this->assertEquals(3, $query->first()->id);
  2205. }
  2206. /**
  2207. * Tests that it is possible to pass a custom join type for an association when
  2208. * using contain
  2209. *
  2210. * @return void
  2211. */
  2212. public function testContainWithCustomJoinType()
  2213. {
  2214. $table = TableRegistry::get('Articles');
  2215. $table->belongsTo('Authors');
  2216. $articles = $table->find()
  2217. ->contain([
  2218. 'Authors' => [
  2219. 'joinType' => 'inner',
  2220. 'conditions' => ['Authors.id' => 3]
  2221. ]
  2222. ])
  2223. ->toArray();
  2224. $this->assertCount(1, $articles);
  2225. $this->assertEquals(3, $articles[0]->author->id);
  2226. }
  2227. /**
  2228. * Tests that it is possible to override the contain strategy using the
  2229. * containments array. In this case, no inner join will be made and for that
  2230. * reason, the parent association will not be filtered as the strategy changed
  2231. * from join to select.
  2232. *
  2233. * @return void
  2234. */
  2235. public function testContainWithStrategyOverride()
  2236. {
  2237. $table = TableRegistry::get('Articles');
  2238. $table->belongsTo('Authors', [
  2239. 'joinType' => 'INNER'
  2240. ]);
  2241. $articles = $table->find()
  2242. ->contain([
  2243. 'Authors' => [
  2244. 'strategy' => 'select',
  2245. 'conditions' => ['Authors.id' => 3]
  2246. ]
  2247. ])
  2248. ->toArray();
  2249. $this->assertCount(3, $articles);
  2250. $this->assertEquals(3, $articles[1]->author->id);
  2251. $this->assertNull($articles[0]->author);
  2252. $this->assertNull($articles[2]->author);
  2253. }
  2254. /**
  2255. * Tests that it is possible to call matching and contain on the same
  2256. * association.
  2257. *
  2258. * @return void
  2259. */
  2260. public function testMatchingWithContain()
  2261. {
  2262. $query = new Query($this->connection, $this->table);
  2263. $table = TableRegistry::get('authors');
  2264. $table->hasMany('articles');
  2265. TableRegistry::get('articles')->belongsToMany('tags');
  2266. $result = $query->repository($table)
  2267. ->select()
  2268. ->matching('articles.tags', function ($q) {
  2269. return $q->where(['tags.id' => 2]);
  2270. })
  2271. ->contain('articles')
  2272. ->first();
  2273. $this->assertEquals(1, $result->id);
  2274. $this->assertCount(2, $result->articles);
  2275. $this->assertEquals(2, $result->_matchingData['tags']->id);
  2276. }
  2277. /**
  2278. * Tests that it is possible to call matching and contain on the same
  2279. * association with only one level of depth.
  2280. *
  2281. * @return void
  2282. */
  2283. public function testNotSoFarMatchingWithContainOnTheSameAssociation()
  2284. {
  2285. $table = TableRegistry::get('articles');
  2286. $table->belongsToMany('tags');
  2287. $result = $table->find()
  2288. ->matching('tags', function ($q) {
  2289. return $q->where(['tags.id' => 2]);
  2290. })
  2291. ->contain('tags')
  2292. ->first();
  2293. $this->assertEquals(1, $result->id);
  2294. $this->assertCount(2, $result->tags);
  2295. $this->assertEquals(2, $result->_matchingData['tags']->id);
  2296. }
  2297. }