QueryTest.php 117 KB

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