QueryTest.php 76 KB

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