QueryTest.php 81 KB

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