QueryTest.php 77 KB

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