QueryTest.php 115 KB

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