QueryTest.php 77 KB

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