QueryTest.php 78 KB

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