QueryTest.php 77 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526
  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(3))
  940. ->method('fetch')
  941. ->will($this->onConsecutiveCalls(['a' => 1], ['a' => 2], false));
  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. * Tests that first can be called on an unbuffered query
  1028. *
  1029. * @return void
  1030. */
  1031. public function testFirstUnbuffered()
  1032. {
  1033. $table = TableRegistry::get('Articles');
  1034. $query = new Query($this->connection, $table);
  1035. $query->select(['id']);
  1036. $first = $query->hydrate(false)
  1037. ->bufferResults(false)->first();
  1038. $this->assertEquals(['id' => 1], $first);
  1039. }
  1040. /**
  1041. * Testing hydrating a result set into Entity objects
  1042. *
  1043. * @return void
  1044. */
  1045. public function testHydrateSimple()
  1046. {
  1047. $table = TableRegistry::get('articles', ['table' => 'articles']);
  1048. $query = new Query($this->connection, $table);
  1049. $results = $query->select()->toArray();
  1050. $this->assertCount(3, $results);
  1051. foreach ($results as $r) {
  1052. $this->assertInstanceOf('Cake\ORM\Entity', $r);
  1053. }
  1054. $first = $results[0];
  1055. $this->assertEquals(1, $first->id);
  1056. $this->assertEquals(1, $first->author_id);
  1057. $this->assertEquals('First Article', $first->title);
  1058. $this->assertEquals('First Article Body', $first->body);
  1059. $this->assertEquals('Y', $first->published);
  1060. }
  1061. /**
  1062. * Tests that has many results are also hydrated correctly
  1063. *
  1064. * @return void
  1065. */
  1066. public function testHydrateHasMany()
  1067. {
  1068. $table = TableRegistry::get('authors');
  1069. TableRegistry::get('articles');
  1070. $table->hasMany('articles', [
  1071. 'propertyName' => 'articles',
  1072. 'sort' => ['articles.id' => 'asc']
  1073. ]);
  1074. $query = new Query($this->connection, $table);
  1075. $results = $query->select()
  1076. ->contain('articles')
  1077. ->toArray();
  1078. $first = $results[0];
  1079. foreach ($first->articles as $r) {
  1080. $this->assertInstanceOf('Cake\ORM\Entity', $r);
  1081. }
  1082. $this->assertCount(2, $first->articles);
  1083. $expected = [
  1084. 'id' => 1,
  1085. 'title' => 'First Article',
  1086. 'body' => 'First Article Body',
  1087. 'author_id' => 1,
  1088. 'published' => 'Y',
  1089. ];
  1090. $this->assertEquals($expected, $first->articles[0]->toArray());
  1091. $expected = [
  1092. 'id' => 3,
  1093. 'title' => 'Third Article',
  1094. 'author_id' => 1,
  1095. 'body' => 'Third Article Body',
  1096. 'published' => 'Y',
  1097. ];
  1098. $this->assertEquals($expected, $first->articles[1]->toArray());
  1099. }
  1100. /**
  1101. * Tests that belongsToMany associations are also correctly hydrated
  1102. *
  1103. * @return void
  1104. */
  1105. public function testHydrateBelongsToMany()
  1106. {
  1107. $table = TableRegistry::get('Articles');
  1108. TableRegistry::get('Tags');
  1109. TableRegistry::get('ArticlesTags', [
  1110. 'table' => 'articles_tags'
  1111. ]);
  1112. $table->belongsToMany('Tags');
  1113. $query = new Query($this->connection, $table);
  1114. $results = $query
  1115. ->select()
  1116. ->contain('Tags')
  1117. ->toArray();
  1118. $first = $results[0];
  1119. foreach ($first->tags as $r) {
  1120. $this->assertInstanceOf('Cake\ORM\Entity', $r);
  1121. }
  1122. $this->assertCount(2, $first->tags);
  1123. $expected = [
  1124. 'id' => 1,
  1125. 'name' => 'tag1',
  1126. '_joinData' => ['article_id' => 1, 'tag_id' => 1]
  1127. ];
  1128. $this->assertEquals($expected, $first->tags[0]->toArray());
  1129. $expected = [
  1130. 'id' => 2,
  1131. 'name' => 'tag2',
  1132. '_joinData' => ['article_id' => 1, 'tag_id' => 2]
  1133. ];
  1134. $this->assertEquals($expected, $first->tags[1]->toArray());
  1135. }
  1136. /**
  1137. * Tests that belongsToMany associations are also correctly hydrated
  1138. *
  1139. * @return void
  1140. */
  1141. public function testFormatResultsBelongsToMany()
  1142. {
  1143. $table = TableRegistry::get('Articles');
  1144. TableRegistry::get('Tags');
  1145. $articlesTags = TableRegistry::get('ArticlesTags', [
  1146. 'table' => 'articles_tags'
  1147. ]);
  1148. $table->belongsToMany('Tags');
  1149. $articlesTags
  1150. ->eventManager()
  1151. ->attach(function ($event, $query) {
  1152. $query->formatResults(function ($results) {
  1153. return $results;
  1154. });
  1155. }, 'Model.beforeFind');
  1156. $query = new Query($this->connection, $table);
  1157. $results = $query
  1158. ->select()
  1159. ->contain('Tags')
  1160. ->toArray();
  1161. $first = $results[0];
  1162. foreach ($first->tags as $r) {
  1163. $this->assertInstanceOf('Cake\ORM\Entity', $r);
  1164. }
  1165. $this->assertCount(2, $first->tags);
  1166. $expected = [
  1167. 'id' => 1,
  1168. 'name' => 'tag1',
  1169. '_joinData' => ['article_id' => 1, 'tag_id' => 1]
  1170. ];
  1171. $this->assertEquals($expected, $first->tags[0]->toArray());
  1172. $expected = [
  1173. 'id' => 2,
  1174. 'name' => 'tag2',
  1175. '_joinData' => ['article_id' => 1, 'tag_id' => 2]
  1176. ];
  1177. $this->assertEquals($expected, $first->tags[1]->toArray());
  1178. }
  1179. /**
  1180. * Tests that belongsTo relations are correctly hydrated
  1181. *
  1182. * @dataProvider internalStategiesProvider
  1183. * @return void
  1184. */
  1185. public function testHydrateBelongsTo($strategy)
  1186. {
  1187. $table = TableRegistry::get('articles');
  1188. TableRegistry::get('authors');
  1189. $table->belongsTo('authors', ['strategy' => $strategy]);
  1190. $query = new Query($this->connection, $table);
  1191. $results = $query->select()
  1192. ->contain('authors')
  1193. ->order(['articles.id' => 'asc'])
  1194. ->toArray();
  1195. $this->assertCount(3, $results);
  1196. $first = $results[0];
  1197. $this->assertInstanceOf('Cake\ORM\Entity', $first->author);
  1198. $expected = ['id' => 1, 'name' => 'mariano'];
  1199. $this->assertEquals($expected, $first->author->toArray());
  1200. }
  1201. /**
  1202. * Tests that deeply nested associations are also hydrated correctly
  1203. *
  1204. * @dataProvider internalStategiesProvider
  1205. * @return void
  1206. */
  1207. public function testHydrateDeep($strategy)
  1208. {
  1209. $table = TableRegistry::get('authors');
  1210. $article = TableRegistry::get('articles');
  1211. $table->hasMany('articles', [
  1212. 'propertyName' => 'articles',
  1213. 'sort' => ['articles.id' => 'asc']
  1214. ]);
  1215. $article->belongsTo('authors', ['strategy' => $strategy]);
  1216. $query = new Query($this->connection, $table);
  1217. $results = $query->select()
  1218. ->contain(['articles' => ['authors']])
  1219. ->toArray();
  1220. $this->assertCount(4, $results);
  1221. $first = $results[0];
  1222. $this->assertInstanceOf('Cake\ORM\Entity', $first->articles[0]->author);
  1223. $expected = ['id' => 1, 'name' => 'mariano'];
  1224. $this->assertEquals($expected, $first->articles[0]->author->toArray());
  1225. $this->assertTrue(isset($results[3]->articles));
  1226. }
  1227. /**
  1228. * Tests that it is possible to use a custom entity class
  1229. *
  1230. * @return void
  1231. */
  1232. public function testHydrateCustomObject()
  1233. {
  1234. $class = $this->getMockClass('\Cake\ORM\Entity', ['fakeMethod']);
  1235. $table = TableRegistry::get('articles', [
  1236. 'table' => 'articles',
  1237. 'entityClass' => '\\' . $class
  1238. ]);
  1239. $query = new Query($this->connection, $table);
  1240. $results = $query->select()->toArray();
  1241. $this->assertCount(3, $results);
  1242. foreach ($results as $r) {
  1243. $this->assertInstanceOf($class, $r);
  1244. }
  1245. $first = $results[0];
  1246. $this->assertEquals(1, $first->id);
  1247. $this->assertEquals(1, $first->author_id);
  1248. $this->assertEquals('First Article', $first->title);
  1249. $this->assertEquals('First Article Body', $first->body);
  1250. $this->assertEquals('Y', $first->published);
  1251. }
  1252. /**
  1253. * Tests that has many results are also hydrated correctly
  1254. * when specified a custom entity class
  1255. *
  1256. * @return void
  1257. */
  1258. public function testHydrateHasManyCustomEntity()
  1259. {
  1260. $authorEntity = $this->getMockClass('\Cake\ORM\Entity', ['foo']);
  1261. $articleEntity = $this->getMockClass('\Cake\ORM\Entity', ['foo']);
  1262. $table = TableRegistry::get('authors', [
  1263. 'entityClass' => '\\' . $authorEntity
  1264. ]);
  1265. TableRegistry::get('articles', [
  1266. 'entityClass' => '\\' . $articleEntity
  1267. ]);
  1268. $table->hasMany('articles', [
  1269. 'propertyName' => 'articles',
  1270. 'sort' => ['articles.id' => 'asc']
  1271. ]);
  1272. $query = new Query($this->connection, $table);
  1273. $results = $query->select()
  1274. ->contain('articles')
  1275. ->toArray();
  1276. $first = $results[0];
  1277. $this->assertInstanceOf($authorEntity, $first);
  1278. foreach ($first->articles as $r) {
  1279. $this->assertInstanceOf($articleEntity, $r);
  1280. }
  1281. $this->assertCount(2, $first->articles);
  1282. $expected = [
  1283. 'id' => 1,
  1284. 'title' => 'First Article',
  1285. 'body' => 'First Article Body',
  1286. 'author_id' => 1,
  1287. 'published' => 'Y',
  1288. ];
  1289. $this->assertEquals($expected, $first->articles[0]->toArray());
  1290. }
  1291. /**
  1292. * Tests that belongsTo relations are correctly hydrated into a custom entity class
  1293. *
  1294. * @return void
  1295. */
  1296. public function testHydrateBelongsToCustomEntity()
  1297. {
  1298. $authorEntity = $this->getMockClass('\Cake\ORM\Entity', ['foo']);
  1299. $table = TableRegistry::get('articles');
  1300. TableRegistry::get('authors', [
  1301. 'entityClass' => '\\' . $authorEntity
  1302. ]);
  1303. $table->belongsTo('authors');
  1304. $query = new Query($this->connection, $table);
  1305. $results = $query->select()
  1306. ->contain('authors')
  1307. ->order(['articles.id' => 'asc'])
  1308. ->toArray();
  1309. $first = $results[0];
  1310. $this->assertInstanceOf($authorEntity, $first->author);
  1311. }
  1312. /**
  1313. * Test getting counts from queries.
  1314. *
  1315. * @return void
  1316. */
  1317. public function testCount()
  1318. {
  1319. $table = TableRegistry::get('articles');
  1320. $result = $table->find('all')->count();
  1321. $this->assertSame(3, $result);
  1322. $query = $table->find('all')
  1323. ->where(['id >' => 1])
  1324. ->limit(1);
  1325. $result = $query->count();
  1326. $this->assertSame(2, $result);
  1327. $result = $query->all();
  1328. $this->assertCount(1, $result);
  1329. $this->assertEquals(2, $result->first()->id);
  1330. }
  1331. /**
  1332. * test count with a beforeFind.
  1333. *
  1334. * @return void
  1335. */
  1336. public function testCountBeforeFind()
  1337. {
  1338. $table = TableRegistry::get('Articles');
  1339. $table->hasMany('Comments');
  1340. $table->eventManager()
  1341. ->attach(function ($event, $query) {
  1342. $query
  1343. ->limit(1)
  1344. ->order(['Articles.title' => 'DESC']);
  1345. }, 'Model.beforeFind');
  1346. $query = $table->find();
  1347. $result = $query->count();
  1348. $this->assertSame(3, $result);
  1349. }
  1350. /**
  1351. * Test that count() returns correct results with group by.
  1352. *
  1353. * @return void
  1354. */
  1355. public function testCountWithGroup()
  1356. {
  1357. $table = TableRegistry::get('articles');
  1358. $query = $table->find('all');
  1359. $query->select(['author_id', 's' => $query->func()->sum('id')])
  1360. ->group(['author_id']);
  1361. $result = $query->count();
  1362. $this->assertEquals(2, $result);
  1363. }
  1364. /**
  1365. * Tests that it is possible to provide a callback for calculating the count
  1366. * of a query
  1367. *
  1368. * @return void
  1369. */
  1370. public function testCountWithCustomCounter()
  1371. {
  1372. $table = TableRegistry::get('articles');
  1373. $query = $table->find('all');
  1374. $query
  1375. ->select(['author_id', 's' => $query->func()->sum('id')])
  1376. ->where(['id >' => 2])
  1377. ->group(['author_id'])
  1378. ->counter(function ($q) use ($query) {
  1379. $this->assertNotSame($q, $query);
  1380. return $q->select([], true)->group([], true)->count();
  1381. });
  1382. $result = $query->count();
  1383. $this->assertEquals(1, $result);
  1384. }
  1385. /**
  1386. * Test update method.
  1387. *
  1388. * @return void
  1389. */
  1390. public function testUpdate()
  1391. {
  1392. $table = TableRegistry::get('articles');
  1393. $result = $table->query()
  1394. ->update()
  1395. ->set(['title' => 'First'])
  1396. ->execute();
  1397. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  1398. $this->assertTrue($result->rowCount() > 0);
  1399. }
  1400. /**
  1401. * Test insert method.
  1402. *
  1403. * @return void
  1404. */
  1405. public function testInsert()
  1406. {
  1407. $table = TableRegistry::get('articles');
  1408. $result = $table->query()
  1409. ->insert(['title'])
  1410. ->values(['title' => 'First'])
  1411. ->values(['title' => 'Second'])
  1412. ->execute();
  1413. $result->closeCursor();
  1414. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  1415. //PDO_SQLSRV returns -1 for successful inserts when using INSERT ... OUTPUT
  1416. if (!$this->connection->driver() instanceof \Cake\Database\Driver\Sqlserver) {
  1417. $this->assertEquals(2, $result->rowCount());
  1418. } else {
  1419. $this->assertEquals(-1, $result->rowCount());
  1420. }
  1421. }
  1422. /**
  1423. * Test delete method.
  1424. *
  1425. * @return void
  1426. */
  1427. public function testDelete()
  1428. {
  1429. $table = TableRegistry::get('articles');
  1430. $result = $table->query()
  1431. ->delete()
  1432. ->where(['id >=' => 1])
  1433. ->execute();
  1434. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  1435. $this->assertTrue($result->rowCount() > 0);
  1436. }
  1437. /**
  1438. * Provides a list of collection methods that can be proxied
  1439. * from the query
  1440. *
  1441. * @return array
  1442. */
  1443. public function collectionMethodsProvider()
  1444. {
  1445. $identity = function ($a) {
  1446. return $a;
  1447. };
  1448. return [
  1449. ['filter', $identity],
  1450. ['reject', $identity],
  1451. ['every', $identity],
  1452. ['some', $identity],
  1453. ['contains', $identity],
  1454. ['map', $identity],
  1455. ['reduce', $identity],
  1456. ['extract', $identity],
  1457. ['max', $identity],
  1458. ['min', $identity],
  1459. ['sortBy', $identity],
  1460. ['groupBy', $identity],
  1461. ['countBy', $identity],
  1462. ['shuffle', $identity],
  1463. ['sample', $identity],
  1464. ['take', 1],
  1465. ['append', new \ArrayIterator],
  1466. ['compile', 1],
  1467. ];
  1468. }
  1469. /**
  1470. * Tests that query can proxy collection methods
  1471. *
  1472. * @dataProvider collectionMethodsProvider
  1473. * @return void
  1474. */
  1475. public function testCollectionProxy($method, $arg)
  1476. {
  1477. $query = $this->getMock(
  1478. '\Cake\ORM\Query',
  1479. ['all'],
  1480. [$this->connection, $this->table]
  1481. );
  1482. $query->select();
  1483. $resultSet = $this->getMock('\Cake\ORM\ResultSet', [], [$query, null]);
  1484. $query->expects($this->once())
  1485. ->method('all')
  1486. ->will($this->returnValue($resultSet));
  1487. $resultSet->expects($this->once())
  1488. ->method($method)
  1489. ->with($arg, 'extra')
  1490. ->will($this->returnValue(new \Cake\Collection\Collection([])));
  1491. $this->assertInstanceOf(
  1492. '\Cake\Collection\Collection',
  1493. $query->{$method}($arg, 'extra')
  1494. );
  1495. }
  1496. /**
  1497. * Tests that calling an inexistent method in query throws an
  1498. * exception
  1499. *
  1500. * @expectedException \BadMethodCallException
  1501. * @expectedExceptionMessage Unknown method "derpFilter"
  1502. * @return void
  1503. */
  1504. public function testCollectionProxyBadMethod()
  1505. {
  1506. TableRegistry::get('articles')->find('all')->derpFilter();
  1507. }
  1508. /**
  1509. * cache() should fail on non select queries.
  1510. *
  1511. * @expectedException \RuntimeException
  1512. * @return void
  1513. */
  1514. public function testCacheErrorOnNonSelect()
  1515. {
  1516. $table = TableRegistry::get('articles', ['table' => 'articles']);
  1517. $query = new Query($this->connection, $table);
  1518. $query->insert(['test']);
  1519. $query->cache('my_key');
  1520. }
  1521. /**
  1522. * Integration test for query caching.
  1523. *
  1524. * @return void
  1525. */
  1526. public function testCacheReadIntegration()
  1527. {
  1528. $query = $this->getMock(
  1529. '\Cake\ORM\Query',
  1530. ['execute'],
  1531. [$this->connection, $this->table]
  1532. );
  1533. $resultSet = $this->getMock('\Cake\ORM\ResultSet', [], [$query, null]);
  1534. $query->expects($this->never())
  1535. ->method('execute');
  1536. $cacher = $this->getMock('Cake\Cache\CacheEngine');
  1537. $cacher->expects($this->once())
  1538. ->method('read')
  1539. ->with('my_key')
  1540. ->will($this->returnValue($resultSet));
  1541. $query->cache('my_key', $cacher)
  1542. ->where(['id' => 1]);
  1543. $results = $query->all();
  1544. $this->assertSame($resultSet, $results);
  1545. }
  1546. /**
  1547. * Integration test for query caching.
  1548. *
  1549. * @return void
  1550. */
  1551. public function testCacheWriteIntegration()
  1552. {
  1553. $table = TableRegistry::get('Articles');
  1554. $query = new Query($this->connection, $table);
  1555. $query->select(['id', 'title']);
  1556. $cacher = $this->getMock('Cake\Cache\CacheEngine');
  1557. $cacher->expects($this->once())
  1558. ->method('write')
  1559. ->with(
  1560. 'my_key',
  1561. $this->isInstanceOf('Cake\Datasource\ResultSetInterface')
  1562. );
  1563. $query->cache('my_key', $cacher)
  1564. ->where(['id' => 1]);
  1565. $query->all();
  1566. }
  1567. /**
  1568. * Integration test to show filtering associations using contain and a closure
  1569. *
  1570. * @return void
  1571. */
  1572. public function testContainWithClosure()
  1573. {
  1574. $table = TableRegistry::get('authors');
  1575. $table->hasMany('articles');
  1576. $query = new Query($this->connection, $table);
  1577. $query
  1578. ->select()
  1579. ->contain(['articles' => function ($q) {
  1580. return $q->where(['articles.id' => 1]);
  1581. }]);
  1582. $ids = [];
  1583. foreach ($query as $entity) {
  1584. foreach ((array)$entity->articles as $article) {
  1585. $ids[] = $article->id;
  1586. }
  1587. }
  1588. $this->assertEquals([1], array_unique($ids));
  1589. }
  1590. /**
  1591. * Integration test to ensure that filtering associations with the queryBuilder
  1592. * option works.
  1593. *
  1594. * @expectedException \RuntimeException
  1595. * @return void
  1596. */
  1597. public function testContainWithQueryBuilderHasManyError()
  1598. {
  1599. $table = TableRegistry::get('Authors');
  1600. $table->hasMany('Articles');
  1601. $query = new Query($this->connection, $table);
  1602. $query->select()
  1603. ->contain([
  1604. 'Articles' => [
  1605. 'foreignKey' => false,
  1606. 'queryBuilder' => function ($q) {
  1607. return $q->where(['articles.id' => 1]);
  1608. }
  1609. ]
  1610. ]);
  1611. $query->toArray();
  1612. }
  1613. /**
  1614. * Integration test to ensure that filtering associations with the queryBuilder
  1615. * option works.
  1616. *
  1617. * @return void
  1618. */
  1619. public function testContainWithQueryBuilderJoinableAssociation()
  1620. {
  1621. $table = TableRegistry::get('Authors');
  1622. $table->hasOne('Articles');
  1623. $query = new Query($this->connection, $table);
  1624. $query->select()
  1625. ->contain([
  1626. 'Articles' => [
  1627. 'foreignKey' => false,
  1628. 'queryBuilder' => function ($q) {
  1629. return $q->where(['Articles.id' => 1]);
  1630. }
  1631. ]
  1632. ]);
  1633. $result = $query->toArray();
  1634. $this->assertEquals(1, $result[0]->article->id);
  1635. $this->assertEquals(1, $result[1]->article->id);
  1636. $articles = TableRegistry::get('Articles');
  1637. $articles->belongsTo('Authors');
  1638. $query = new Query($this->connection, $articles);
  1639. $query->select()
  1640. ->contain([
  1641. 'Authors' => [
  1642. 'foreignKey' => false,
  1643. 'queryBuilder' => function ($q) {
  1644. return $q->where(['Authors.id' => 1]);
  1645. }
  1646. ]
  1647. ]);
  1648. $result = $query->toArray();
  1649. $this->assertEquals(1, $result[0]->author->id);
  1650. }
  1651. /**
  1652. * Tests the formatResults method
  1653. *
  1654. * @return void
  1655. */
  1656. public function testFormatResults()
  1657. {
  1658. $callback1 = function () {
  1659. };
  1660. $callback2 = function () {
  1661. };
  1662. $table = TableRegistry::get('authors');
  1663. $query = new Query($this->connection, $table);
  1664. $this->assertSame($query, $query->formatResults($callback1));
  1665. $this->assertSame([$callback1], $query->formatResults());
  1666. $this->assertSame($query, $query->formatResults($callback2));
  1667. $this->assertSame([$callback1, $callback2], $query->formatResults());
  1668. $query->formatResults($callback2, true);
  1669. $this->assertSame([$callback2], $query->formatResults());
  1670. $query->formatResults(null, true);
  1671. $this->assertSame([], $query->formatResults());
  1672. $query->formatResults($callback1);
  1673. $query->formatResults($callback2, $query::PREPEND);
  1674. $this->assertSame([$callback2, $callback1], $query->formatResults());
  1675. }
  1676. /**
  1677. * Test fetching results from a qurey with a custom formatter
  1678. *
  1679. * @return void
  1680. */
  1681. public function testQueryWithFormatter()
  1682. {
  1683. $table = TableRegistry::get('authors');
  1684. $query = new Query($this->connection, $table);
  1685. $query->select()->formatResults(function ($results) {
  1686. $this->assertInstanceOf('Cake\ORM\ResultSet', $results);
  1687. return $results->indexBy('id');
  1688. });
  1689. $this->assertEquals([1, 2, 3, 4], array_keys($query->toArray()));
  1690. }
  1691. /**
  1692. * Test fetching results from a qurey with a two custom formatters
  1693. *
  1694. * @return void
  1695. */
  1696. public function testQueryWithStackedFormatters()
  1697. {
  1698. $table = TableRegistry::get('authors');
  1699. $query = new Query($this->connection, $table);
  1700. $query->select()->formatResults(function ($results) {
  1701. $this->assertInstanceOf('Cake\ORM\ResultSet', $results);
  1702. return $results->indexBy('id');
  1703. });
  1704. $query->formatResults(function ($results) {
  1705. return $results->extract('name');
  1706. });
  1707. $expected = [
  1708. 1 => 'mariano',
  1709. 2 => 'nate',
  1710. 3 => 'larry',
  1711. 4 => 'garrett'
  1712. ];
  1713. $this->assertEquals($expected, $query->toArray());
  1714. }
  1715. /**
  1716. * Tests that getting results from a query having a contained association
  1717. * will no attach joins twice if count() is called on it afterwards
  1718. *
  1719. * @return void
  1720. */
  1721. public function testCountWithContainCallingAll()
  1722. {
  1723. $table = TableRegistry::get('articles');
  1724. $table->belongsTo('authors');
  1725. $query = $table->find()
  1726. ->select(['id', 'title'])
  1727. ->contain('authors')
  1728. ->limit(2);
  1729. $results = $query->all();
  1730. $this->assertCount(2, $results);
  1731. $this->assertEquals(3, $query->count());
  1732. }
  1733. /**
  1734. * Tests that it is possible to apply formatters inside the query builder
  1735. * for belongsTo associations
  1736. *
  1737. * @return void
  1738. */
  1739. public function testFormatBelongsToRecords()
  1740. {
  1741. $table = TableRegistry::get('articles');
  1742. $table->belongsTo('authors');
  1743. $query = $table->find()
  1744. ->contain(['authors' => function ($q) {
  1745. return $q
  1746. ->formatResults(function ($authors) {
  1747. return $authors->map(function ($author) {
  1748. $author->idCopy = $author->id;
  1749. return $author;
  1750. });
  1751. })
  1752. ->formatResults(function ($authors) {
  1753. return $authors->map(function ($author) {
  1754. $author->idCopy = $author->idCopy + 2;
  1755. return $author;
  1756. });
  1757. });
  1758. }]);
  1759. $query->formatResults(function ($results) {
  1760. return $results->combine('id', 'author.idCopy');
  1761. });
  1762. $results = $query->toArray();
  1763. $expected = [1 => 3, 2 => 5, 3 => 3];
  1764. $this->assertEquals($expected, $results);
  1765. }
  1766. /**
  1767. * Tests it is possible to apply formatters to deep relations.
  1768. *
  1769. * @return void
  1770. */
  1771. public function testFormatDeepAssocationRecords()
  1772. {
  1773. $table = TableRegistry::get('ArticlesTags');
  1774. $table->belongsTo('Articles');
  1775. $table->association('Articles')->target()->belongsTo('Authors');
  1776. $builder = function ($q) {
  1777. return $q
  1778. ->formatResults(function ($results) {
  1779. return $results->map(function ($result) {
  1780. $result->idCopy = $result->id;
  1781. return $result;
  1782. });
  1783. })
  1784. ->formatResults(function ($results) {
  1785. return $results->map(function ($result) {
  1786. $result->idCopy = $result->idCopy + 2;
  1787. return $result;
  1788. });
  1789. });
  1790. };
  1791. $query = $table->find()
  1792. ->contain(['Articles' => $builder, 'Articles.Authors' => $builder])
  1793. ->order(['Articles.id' => 'ASC']);
  1794. $query->formatResults(function ($results) {
  1795. return $results->map(function ($row) {
  1796. return sprintf(
  1797. '%s - %s - %s',
  1798. $row->tag_id,
  1799. $row->article->idCopy,
  1800. $row->article->author->idCopy
  1801. );
  1802. });
  1803. });
  1804. $expected = ['1 - 3 - 3', '2 - 3 - 3', '1 - 4 - 5', '3 - 4 - 5'];
  1805. $this->assertEquals($expected, $query->toArray());
  1806. }
  1807. /**
  1808. * Tests that formatters cna be applied to deep associations that are fetched using
  1809. * additional queries
  1810. *
  1811. * @return void
  1812. */
  1813. public function testFormatDeepDistantAssociationRecords()
  1814. {
  1815. $table = TableRegistry::get('authors');
  1816. $table->hasMany('articles');
  1817. $articles = $table->association('articles')->target();
  1818. $articles->hasMany('articlesTags');
  1819. $articles->association('articlesTags')->target()->belongsTo('tags');
  1820. $query = $table->find()->contain(['articles.articlesTags.tags' => function ($q) {
  1821. return $q->formatResults(function ($results) {
  1822. return $results->map(function ($tag) {
  1823. $tag->name .= ' - visited';
  1824. return $tag;
  1825. });
  1826. });
  1827. }]);
  1828. $query->mapReduce(function ($row, $key, $mr) {
  1829. foreach ((array)$row->articles as $article) {
  1830. foreach ((array)$article->articles_tags as $articleTag) {
  1831. $mr->emit($articleTag->tag->name);
  1832. }
  1833. }
  1834. });
  1835. $expected = ['tag1 - visited', 'tag2 - visited', 'tag1 - visited', 'tag3 - visited'];
  1836. $this->assertEquals($expected, $query->toArray());
  1837. }
  1838. /**
  1839. * Tests that custom finders are applied to associations when using the proxies
  1840. *
  1841. * @return void
  1842. */
  1843. public function testCustomFinderInBelongsTo()
  1844. {
  1845. $table = TableRegistry::get('ArticlesTags');
  1846. $table->belongsTo('Articles', [
  1847. 'className' => 'TestApp\Model\Table\ArticlesTable',
  1848. 'finder' => 'published'
  1849. ]);
  1850. $result = $table->find()->contain('Articles');
  1851. $this->assertCount(4, $result->extract('article')->filter()->toArray());
  1852. $table->Articles->updateAll(['published' => 'N'], ['1 = 1']);
  1853. $result = $table->find()->contain('Articles');
  1854. $this->assertCount(0, $result->extract('article')->filter()->toArray());
  1855. }
  1856. /**
  1857. * Tests that it is possible to attach more association when using a query
  1858. * builder for other associations
  1859. *
  1860. * @return void
  1861. */
  1862. public function testContainInAssociationQuery()
  1863. {
  1864. $table = TableRegistry::get('ArticlesTags');
  1865. $table->belongsTo('Articles');
  1866. $table->association('Articles')->target()->belongsTo('Authors');
  1867. $query = $table->find()
  1868. ->order(['Articles.id' => 'ASC'])
  1869. ->contain(['Articles' => function ($q) {
  1870. return $q->contain('Authors');
  1871. }]);
  1872. $results = $query->extract('article.author.name')->toArray();
  1873. $expected = ['mariano', 'mariano', 'larry', 'larry'];
  1874. $this->assertEquals($expected, $results);
  1875. }
  1876. /**
  1877. * Tests that it is possible to apply more `matching` conditions inside query
  1878. * builders for associations
  1879. *
  1880. * @return void
  1881. */
  1882. public function testContainInAssociationMatching()
  1883. {
  1884. $table = TableRegistry::get('authors');
  1885. $table->hasMany('articles');
  1886. $articles = $table->association('articles')->target();
  1887. $articles->hasMany('articlesTags');
  1888. $articles->association('articlesTags')->target()->belongsTo('tags');
  1889. $query = $table->find()->matching('articles.articlesTags', function ($q) {
  1890. return $q->matching('tags', function ($q) {
  1891. return $q->where(['tags.name' => 'tag3']);
  1892. });
  1893. });
  1894. $results = $query->toArray();
  1895. $this->assertCount(1, $results);
  1896. $this->assertEquals('tag3', $results[0]->_matchingData['tags']->name);
  1897. }
  1898. /**
  1899. * Tests __debugInfo
  1900. *
  1901. * @return void
  1902. */
  1903. public function testDebugInfo()
  1904. {
  1905. $table = TableRegistry::get('authors');
  1906. $table->hasMany('articles');
  1907. $query = $table->find()
  1908. ->where(['id > ' => 1])
  1909. ->bufferResults(false)
  1910. ->hydrate(false)
  1911. ->matching('articles')
  1912. ->applyOptions(['foo' => 'bar'])
  1913. ->formatResults(function ($results) {
  1914. return $results;
  1915. })
  1916. ->mapReduce(function ($item, $key, $mr) {
  1917. $mr->emit($item);
  1918. });
  1919. $expected = [
  1920. 'sql' => $query->sql(),
  1921. 'params' => $query->valueBinder()->bindings(),
  1922. 'defaultTypes' => [
  1923. 'authors.id' => 'integer',
  1924. 'id' => 'integer',
  1925. 'authors.name' => 'string',
  1926. 'name' => 'string'
  1927. ],
  1928. 'decorators' => 0,
  1929. 'executed' => false,
  1930. 'hydrate' => false,
  1931. 'buffered' => false,
  1932. 'formatters' => 1,
  1933. 'mapReducers' => 1,
  1934. 'contain' => [],
  1935. 'matching' => [
  1936. 'articles' => [
  1937. 'queryBuilder' => null,
  1938. 'matching' => true
  1939. ]
  1940. ],
  1941. 'extraOptions' => ['foo' => 'bar'],
  1942. 'repository' => $table
  1943. ];
  1944. $this->assertSame($expected, $query->__debugInfo());
  1945. }
  1946. /**
  1947. * Tests that the eagerLoaded function works and is transmitted correctly to eagerly
  1948. * loaded associations
  1949. *
  1950. * @return void
  1951. */
  1952. public function testEagerLoaded()
  1953. {
  1954. $table = TableRegistry::get('authors');
  1955. $table->hasMany('articles');
  1956. $query = $table->find()->contain(['articles' => function ($q) {
  1957. $this->assertTrue($q->eagerLoaded());
  1958. return $q;
  1959. }]);
  1960. $this->assertFalse($query->eagerLoaded());
  1961. $table->eventManager()->attach(function ($e, $q, $o, $primary) {
  1962. $this->assertTrue($primary);
  1963. }, 'Model.beforeFind');
  1964. TableRegistry::get('articles')
  1965. ->eventManager()->attach(function ($e, $q, $o, $primary) {
  1966. $this->assertFalse($primary);
  1967. }, 'Model.beforeFind');
  1968. $query->all();
  1969. }
  1970. /**
  1971. * Tests that columns from manual joins are also contained in the result set
  1972. *
  1973. * @return void
  1974. */
  1975. public function testColumnsFromJoin()
  1976. {
  1977. $table = TableRegistry::get('articles');
  1978. $results = $table->find()
  1979. ->select(['title', 'person.name'])
  1980. ->join([
  1981. 'person' => [
  1982. 'table' => 'authors',
  1983. 'conditions' => ['person.id = articles.author_id']
  1984. ]
  1985. ])
  1986. ->order(['articles.id' => 'ASC'])
  1987. ->hydrate(false)
  1988. ->toArray();
  1989. $expected = [
  1990. ['title' => 'First Article', 'person' => ['name' => 'mariano']],
  1991. ['title' => 'Second Article', 'person' => ['name' => 'larry']],
  1992. ['title' => 'Third Article', 'person' => ['name' => 'mariano']],
  1993. ];
  1994. $this->assertSame($expected, $results);
  1995. }
  1996. /**
  1997. * Tests that it is possible to use the same association aliases in the association
  1998. * chain for contain
  1999. *
  2000. * @dataProvider internalStategiesProvider
  2001. * @return void
  2002. */
  2003. public function testRepeatedAssociationAliases($strategy)
  2004. {
  2005. $table = TableRegistry::get('ArticlesTags');
  2006. $table->belongsTo('Articles', ['strategy' => $strategy]);
  2007. $table->belongsTo('Tags', ['strategy' => $strategy]);
  2008. TableRegistry::get('Tags')->belongsToMany('Articles');
  2009. $results = $table
  2010. ->find()
  2011. ->contain(['Articles', 'Tags.Articles'])
  2012. ->hydrate(false)
  2013. ->toArray();
  2014. $this->assertNotEmpty($results[0]['tag']['articles']);
  2015. $this->assertNotEmpty($results[0]['article']);
  2016. $this->assertNotEmpty($results[1]['tag']['articles']);
  2017. $this->assertNotEmpty($results[1]['article']);
  2018. $this->assertNotEmpty($results[2]['tag']['articles']);
  2019. $this->assertNotEmpty($results[2]['article']);
  2020. }
  2021. /**
  2022. * Tests that a hasOne association using the select strategy will still have the
  2023. * key present in the results when no match is found
  2024. *
  2025. * @return void
  2026. */
  2027. public function testAssociationKeyPresent()
  2028. {
  2029. $table = TableRegistry::get('Articles');
  2030. $table->hasOne('ArticlesTags', ['strategy' => 'select']);
  2031. $article = $table->find()->where(['id' => 3])
  2032. ->hydrate(false)
  2033. ->contain('ArticlesTags')
  2034. ->first();
  2035. $this->assertNull($article['articles_tag']);
  2036. }
  2037. /**
  2038. * Tests that queries can be serialized to JSON to get the results
  2039. *
  2040. * @return void
  2041. */
  2042. public function testJsonSerialize()
  2043. {
  2044. $table = TableRegistry::get('Articles');
  2045. $this->assertEquals(
  2046. json_encode($table->find()),
  2047. json_encode($table->find()->toArray())
  2048. );
  2049. }
  2050. /**
  2051. * Test that addFields() works in the basic case.
  2052. *
  2053. * @return void
  2054. */
  2055. public function testAutoFields()
  2056. {
  2057. $table = TableRegistry::get('Articles');
  2058. $result = $table->find('all')
  2059. ->select(['myField' => '(SELECT 20)'])
  2060. ->autoFields(true)
  2061. ->hydrate(false)
  2062. ->first();
  2063. $this->assertArrayHasKey('myField', $result);
  2064. $this->assertArrayHasKey('id', $result);
  2065. $this->assertArrayHasKey('title', $result);
  2066. }
  2067. /**
  2068. * Test autoFields with auto fields.
  2069. *
  2070. * @return void
  2071. */
  2072. public function testAutoFieldsWithAssociations()
  2073. {
  2074. $table = TableRegistry::get('Articles');
  2075. $table->belongsTo('Authors');
  2076. $result = $table->find()
  2077. ->select(['myField' => '(SELECT 2 + 2)'])
  2078. ->autoFields(true)
  2079. ->hydrate(false)
  2080. ->contain('Authors')
  2081. ->first();
  2082. $this->assertArrayHasKey('myField', $result);
  2083. $this->assertArrayHasKey('title', $result);
  2084. $this->assertArrayHasKey('author', $result);
  2085. $this->assertNotNull($result['author']);
  2086. $this->assertArrayHasKey('name', $result['author']);
  2087. }
  2088. /**
  2089. * Test autoFields in contain query builder
  2090. *
  2091. * @return void
  2092. */
  2093. public function testAutoFieldsWithContainQueryBuilder()
  2094. {
  2095. $table = TableRegistry::get('Articles');
  2096. $table->belongsTo('Authors');
  2097. $result = $table->find()
  2098. ->select(['myField' => '(SELECT 2 + 2)'])
  2099. ->autoFields(true)
  2100. ->hydrate(false)
  2101. ->contain(['Authors' => function ($q) {
  2102. return $q->select(['compute' => '(SELECT 2 + 20)'])
  2103. ->autoFields(true);
  2104. }])
  2105. ->first();
  2106. $this->assertArrayHasKey('myField', $result);
  2107. $this->assertArrayHasKey('title', $result);
  2108. $this->assertArrayHasKey('author', $result);
  2109. $this->assertNotNull($result['author']);
  2110. $this->assertArrayHasKey('name', $result['author']);
  2111. $this->assertArrayHasKey('compute', $result);
  2112. }
  2113. /**
  2114. * Test that autofields works with count()
  2115. *
  2116. * @return void
  2117. */
  2118. public function testAutoFieldsCount()
  2119. {
  2120. $table = TableRegistry::get('Articles');
  2121. $result = $table->find()
  2122. ->select(['myField' => '(SELECT (2 + 2))'])
  2123. ->autoFields(true)
  2124. ->count();
  2125. $this->assertEquals(3, $result);
  2126. }
  2127. /**
  2128. * test that cleanCopy makes a cleaned up clone.
  2129. *
  2130. * @return void
  2131. */
  2132. public function testCleanCopy()
  2133. {
  2134. $table = TableRegistry::get('Articles');
  2135. $table->hasMany('Comments');
  2136. $query = $table->find();
  2137. $query->offset(10)
  2138. ->limit(1)
  2139. ->order(['Articles.id' => 'DESC'])
  2140. ->contain(['Comments']);
  2141. $copy = $query->cleanCopy();
  2142. $this->assertNotSame($copy, $query);
  2143. $this->assertNull($copy->clause('offset'));
  2144. $this->assertNull($copy->clause('limit'));
  2145. $this->assertNull($copy->clause('order'));
  2146. }
  2147. /**
  2148. * test that cleanCopy makes a cleaned up clone with a beforeFind.
  2149. *
  2150. * @return void
  2151. */
  2152. public function testCleanCopyBeforeFind()
  2153. {
  2154. $table = TableRegistry::get('Articles');
  2155. $table->hasMany('Comments');
  2156. $table->eventManager()
  2157. ->attach(function ($event, $query) {
  2158. $query
  2159. ->limit(5)
  2160. ->order(['Articles.title' => 'DESC']);
  2161. }, 'Model.beforeFind');
  2162. $query = $table->find();
  2163. $query->offset(10)
  2164. ->limit(1)
  2165. ->order(['Articles.id' => 'DESC'])
  2166. ->contain(['Comments']);
  2167. $copy = $query->cleanCopy();
  2168. $this->assertNotSame($copy, $query);
  2169. $this->assertNull($copy->clause('offset'));
  2170. $this->assertNull($copy->clause('limit'));
  2171. $this->assertNull($copy->clause('order'));
  2172. }
  2173. /**
  2174. * Test that finder options sent through via contain are sent to custom finder.
  2175. *
  2176. * @return void
  2177. */
  2178. public function testContainFinderCanSpecifyOptions()
  2179. {
  2180. $table = TableRegistry::get('Articles');
  2181. $table->belongsTo(
  2182. 'Authors',
  2183. ['className' => 'TestApp\Model\Table\AuthorsTable']
  2184. );
  2185. $authorId = 1;
  2186. $resultWithoutAuthor = $table->find('all')
  2187. ->where(['Articles.author_id' => $authorId])
  2188. ->contain([
  2189. 'Authors' => [
  2190. 'finder' => ['byAuthor' => ['author_id' => 2]]
  2191. ]
  2192. ]);
  2193. $resultWithAuthor = $table->find('all')
  2194. ->where(['Articles.author_id' => $authorId])
  2195. ->contain([
  2196. 'Authors' => [
  2197. 'finder' => ['byAuthor' => ['author_id' => $authorId]]
  2198. ]
  2199. ]);
  2200. $this->assertEmpty($resultWithoutAuthor->first()['author']);
  2201. $this->assertEquals($authorId, $resultWithAuthor->first()['author']['id']);
  2202. }
  2203. /**
  2204. * Tests that it is possible to bind arguments to a query and it will return the right
  2205. * results
  2206. *
  2207. * @return void
  2208. */
  2209. public function testCustomBindings()
  2210. {
  2211. $table = TableRegistry::get('Articles');
  2212. $query = $table->find()->where(['id >' => 1]);
  2213. $query->where(function ($exp) {
  2214. return $exp->add('author_id = :author');
  2215. });
  2216. $query->bind(':author', 1, 'integer');
  2217. $this->assertEquals(1, $query->count());
  2218. $this->assertEquals(3, $query->first()->id);
  2219. }
  2220. /**
  2221. * Tests that it is possible to pass a custom join type for an association when
  2222. * using contain
  2223. *
  2224. * @return void
  2225. */
  2226. public function testContainWithCustomJoinType()
  2227. {
  2228. $table = TableRegistry::get('Articles');
  2229. $table->belongsTo('Authors');
  2230. $articles = $table->find()
  2231. ->contain([
  2232. 'Authors' => [
  2233. 'joinType' => 'inner',
  2234. 'conditions' => ['Authors.id' => 3]
  2235. ]
  2236. ])
  2237. ->toArray();
  2238. $this->assertCount(1, $articles);
  2239. $this->assertEquals(3, $articles[0]->author->id);
  2240. }
  2241. /**
  2242. * Tests that it is possible to override the contain strategy using the
  2243. * containments array. In this case, no inner join will be made and for that
  2244. * reason, the parent association will not be filtered as the strategy changed
  2245. * from join to select.
  2246. *
  2247. * @return void
  2248. */
  2249. public function testContainWithStrategyOverride()
  2250. {
  2251. $table = TableRegistry::get('Articles');
  2252. $table->belongsTo('Authors', [
  2253. 'joinType' => 'INNER'
  2254. ]);
  2255. $articles = $table->find()
  2256. ->contain([
  2257. 'Authors' => [
  2258. 'strategy' => 'select',
  2259. 'conditions' => ['Authors.id' => 3]
  2260. ]
  2261. ])
  2262. ->toArray();
  2263. $this->assertCount(3, $articles);
  2264. $this->assertEquals(3, $articles[1]->author->id);
  2265. $this->assertNull($articles[0]->author);
  2266. $this->assertNull($articles[2]->author);
  2267. }
  2268. /**
  2269. * Tests that it is possible to call matching and contain on the same
  2270. * association.
  2271. *
  2272. * @return void
  2273. */
  2274. public function testMatchingWithContain()
  2275. {
  2276. $query = new Query($this->connection, $this->table);
  2277. $table = TableRegistry::get('authors');
  2278. $table->hasMany('articles');
  2279. TableRegistry::get('articles')->belongsToMany('tags');
  2280. $result = $query->repository($table)
  2281. ->select()
  2282. ->matching('articles.tags', function ($q) {
  2283. return $q->where(['tags.id' => 2]);
  2284. })
  2285. ->contain('articles')
  2286. ->first();
  2287. $this->assertEquals(1, $result->id);
  2288. $this->assertCount(2, $result->articles);
  2289. $this->assertEquals(2, $result->_matchingData['tags']->id);
  2290. }
  2291. /**
  2292. * Tests that it is possible to call matching and contain on the same
  2293. * association with only one level of depth.
  2294. *
  2295. * @return void
  2296. */
  2297. public function testNotSoFarMatchingWithContainOnTheSameAssociation()
  2298. {
  2299. $table = TableRegistry::get('articles');
  2300. $table->belongsToMany('tags');
  2301. $result = $table->find()
  2302. ->matching('tags', function ($q) {
  2303. return $q->where(['tags.id' => 2]);
  2304. })
  2305. ->contain('tags')
  2306. ->first();
  2307. $this->assertEquals(1, $result->id);
  2308. $this->assertCount(2, $result->tags);
  2309. $this->assertEquals(2, $result->_matchingData['tags']->id);
  2310. }
  2311. }