QueryTest.php 53 KB

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