QueryTest.php 115 KB

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