QueryTest.php 116 KB

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