QueryTest.php 94 KB

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