QueryRegressionTest.php 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495
  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\Core\Plugin;
  17. use Cake\I18n\Time;
  18. use Cake\ORM\TableRegistry;
  19. use Cake\TestSuite\TestCase;
  20. /**
  21. * Contains regression test for the Query builder
  22. */
  23. class QueryRegressionTest extends TestCase
  24. {
  25. /**
  26. * Fixture to be used
  27. *
  28. * @var array
  29. */
  30. public $fixtures = [
  31. 'core.articles',
  32. 'core.tags',
  33. 'core.articles_tags',
  34. 'core.authors',
  35. 'core.authors_tags',
  36. 'core.comments',
  37. 'core.featured_tags',
  38. 'core.special_tags',
  39. 'core.tags_translations',
  40. 'core.translates',
  41. 'core.users'
  42. ];
  43. public $autoFixtures = false;
  44. /**
  45. * Tear down
  46. *
  47. * @return void
  48. */
  49. public function tearDown()
  50. {
  51. parent::tearDown();
  52. TableRegistry::clear();
  53. }
  54. /**
  55. * Test for https://github.com/cakephp/cakephp/issues/3087
  56. *
  57. * @return void
  58. */
  59. public function testSelectTimestampColumn()
  60. {
  61. $this->loadFixtures('Users');
  62. $table = TableRegistry::get('users');
  63. $user = $table->find()->where(['id' => 1])->first();
  64. $this->assertEquals(new Time('2007-03-17 01:16:23'), $user->created);
  65. $this->assertEquals(new Time('2007-03-17 01:18:31'), $user->updated);
  66. }
  67. /**
  68. * Tests that EagerLoader does not try to create queries for associations having no
  69. * keys to compare against
  70. *
  71. * @return void
  72. */
  73. public function testEagerLoadingFromEmptyResults()
  74. {
  75. $this->loadFixtures('Articles', 'Tags', 'ArticlesTags');
  76. $table = TableRegistry::get('Articles');
  77. $table->belongsToMany('ArticlesTags');
  78. $results = $table->find()->where(['id >' => 100])->contain('ArticlesTags')->toArray();
  79. $this->assertEmpty($results);
  80. }
  81. /**
  82. * Tests that eagerloading belongsToMany with find list fails with a helpful message.
  83. *
  84. * @expectedException \InvalidArgumentException
  85. * @return void
  86. */
  87. public function testEagerLoadingBelongsToManyList()
  88. {
  89. $this->loadFixtures('Articles', 'Tags', 'ArticlesTags');
  90. $table = TableRegistry::get('Articles');
  91. $table->belongsToMany('Tags', [
  92. 'finder' => 'list'
  93. ]);
  94. $table->find()->contain('Tags')->toArray();
  95. }
  96. /**
  97. * Tests that duplicate aliases in contain() can be used, even when they would
  98. * naturally be attached to the query instead of eagerly loaded. What should
  99. * happen here is that One of the duplicates will be changed to be loaded using
  100. * an extra query, but yielding the same results
  101. *
  102. * @return void
  103. */
  104. public function testDuplicateAttachableAliases()
  105. {
  106. $this->loadFixtures('Articles', 'Tags', 'ArticlesTags', 'Authors');
  107. TableRegistry::get('Stuff', ['table' => 'tags']);
  108. TableRegistry::get('Things', ['table' => 'articles_tags']);
  109. $table = TableRegistry::get('Articles');
  110. $table->belongsTo('Authors');
  111. $table->hasOne('Things', ['propertyName' => 'articles_tag']);
  112. $table->Authors->target()->hasOne('Stuff', [
  113. 'foreignKey' => 'id',
  114. 'propertyName' => 'favorite_tag'
  115. ]);
  116. $table->Things->target()->belongsTo('Stuff', [
  117. 'foreignKey' => 'tag_id',
  118. 'propertyName' => 'foo'
  119. ]);
  120. $results = $table->find()
  121. ->contain(['Authors.Stuff', 'Things.Stuff'])
  122. ->order(['Articles.id' => 'ASC'])
  123. ->toArray();
  124. $this->assertCount(5, $results);
  125. $this->assertEquals(1, $results[0]->articles_tag->foo->id);
  126. $this->assertEquals(1, $results[0]->author->favorite_tag->id);
  127. $this->assertEquals(2, $results[1]->articles_tag->foo->id);
  128. $this->assertEquals(1, $results[2]->articles_tag->foo->id);
  129. $this->assertEquals(3, $results[2]->author->favorite_tag->id);
  130. $this->assertEquals(3, $results[3]->articles_tag->foo->id);
  131. $this->assertEquals(3, $results[3]->author->favorite_tag->id);
  132. }
  133. /**
  134. * Test for https://github.com/cakephp/cakephp/issues/3410
  135. *
  136. * @return void
  137. */
  138. public function testNullableTimeColumn()
  139. {
  140. $this->loadFixtures('Users');
  141. $table = TableRegistry::get('users');
  142. $entity = $table->newEntity(['username' => 'derp', 'created' => null]);
  143. $this->assertSame($entity, $table->save($entity));
  144. $this->assertNull($entity->created);
  145. }
  146. /**
  147. * Test for https://github.com/cakephp/cakephp/issues/3626
  148. *
  149. * Checks that join data is actually created and not tried to be updated every time
  150. * @return void
  151. */
  152. public function testCreateJointData()
  153. {
  154. $this->loadFixtures('Articles', 'Tags', 'SpecialTags');
  155. $articles = TableRegistry::get('Articles');
  156. $articles->belongsToMany('Highlights', [
  157. 'className' => 'TestApp\Model\Table\TagsTable',
  158. 'foreignKey' => 'article_id',
  159. 'targetForeignKey' => 'tag_id',
  160. 'through' => 'SpecialTags'
  161. ]);
  162. $entity = $articles->get(2);
  163. $data = [
  164. 'id' => 2,
  165. 'highlights' => [
  166. [
  167. 'name' => 'New Special Tag',
  168. '_joinData' => ['highlighted' => true, 'highlighted_time' => '2014-06-01 10:10:00']
  169. ]
  170. ]
  171. ];
  172. $entity = $articles->patchEntity($entity, $data, ['Highlights._joinData']);
  173. $articles->save($entity);
  174. $entity = $articles->get(2, ['contain' => ['Highlights']]);
  175. $this->assertEquals(4, $entity->highlights[0]->_joinData->tag_id);
  176. $this->assertEquals('2014-06-01', $entity->highlights[0]->_joinData->highlighted_time->format('Y-m-d'));
  177. }
  178. /**
  179. * Tests that the junction table instance taken from both sides of a belongsToMany
  180. * relationship is actually the same object.
  181. *
  182. * @return void
  183. */
  184. public function testReciprocalBelongsToMany()
  185. {
  186. $this->loadFixtures('Articles', 'Tags', 'ArticlesTags');
  187. $articles = TableRegistry::get('Articles');
  188. $tags = TableRegistry::get('Tags');
  189. $articles->belongsToMany('Tags');
  190. $tags->belongsToMany('Articles');
  191. $left = $articles->Tags->junction();
  192. $right = $tags->Articles->junction();
  193. $this->assertSame($left, $right);
  194. }
  195. /**
  196. * Test for https://github.com/cakephp/cakephp/issues/4253
  197. *
  198. * Makes sure that the belongsToMany association is not overwritten with conflicting information
  199. * by any of the sides when the junction() function is invoked
  200. *
  201. * @return void
  202. */
  203. public function testReciprocalBelongsToManyNoOverwrite()
  204. {
  205. $this->loadFixtures('Articles', 'Tags', 'ArticlesTags');
  206. $articles = TableRegistry::get('Articles');
  207. $tags = TableRegistry::get('Tags');
  208. $articles->belongsToMany('Tags');
  209. $tags->belongsToMany('Articles');
  210. $sub = $articles->Tags->find()->select(['Tags.id'])->matching('Articles', function ($q) {
  211. return $q->where(['Articles.id' => 1]);
  212. });
  213. $query = $articles->Tags->find()->where(['Tags.id NOT IN' => $sub]);
  214. $this->assertEquals(1, $query->count());
  215. }
  216. /**
  217. * Returns an array with the saving strategies for a belongsTo association
  218. *
  219. * @return array
  220. */
  221. public function strategyProvider()
  222. {
  223. return [
  224. ['append'],
  225. ['replace'],
  226. ];
  227. }
  228. /**
  229. * Test for https://github.com/cakephp/cakephp/issues/3677 and
  230. * https://github.com/cakephp/cakephp/issues/3714
  231. *
  232. * Checks that only relevant associations are passed when saving _joinData
  233. * Tests that _joinData can also save deeper associations
  234. *
  235. * @dataProvider strategyProvider
  236. * @param string $strategy
  237. * @return void
  238. */
  239. public function testBelongsToManyDeepSave($strategy)
  240. {
  241. $this->loadFixtures('Articles', 'Tags', 'SpecialTags', 'Authors');
  242. $articles = TableRegistry::get('Articles');
  243. $articles->belongsToMany('Highlights', [
  244. 'className' => 'TestApp\Model\Table\TagsTable',
  245. 'foreignKey' => 'article_id',
  246. 'targetForeignKey' => 'tag_id',
  247. 'through' => 'SpecialTags',
  248. 'saveStrategy' => $strategy
  249. ]);
  250. $articles->Highlights->junction()->belongsTo('Authors');
  251. $articles->Highlights->hasOne('Authors', [
  252. 'foreignKey' => 'id'
  253. ]);
  254. $entity = $articles->get(2, ['contain' => ['Highlights']]);
  255. $data = [
  256. 'highlights' => [
  257. [
  258. 'name' => 'New Special Tag',
  259. '_joinData' => [
  260. 'highlighted' => true,
  261. 'highlighted_time' => '2014-06-01 10:10:00',
  262. 'author' => [
  263. 'name' => 'mariano'
  264. ]
  265. ],
  266. 'author' => ['name' => 'mark']
  267. ]
  268. ]
  269. ];
  270. $options = [
  271. 'associated' => [
  272. 'Highlights._joinData.Authors', 'Highlights.Authors'
  273. ]
  274. ];
  275. $entity = $articles->patchEntity($entity, $data, $options);
  276. $articles->save($entity, $options);
  277. $entity = $articles->get(2, [
  278. 'contain' => [
  279. 'SpecialTags' => ['sort' => ['SpecialTags.id' => 'ASC']],
  280. 'SpecialTags.Authors',
  281. 'Highlights.Authors'
  282. ]
  283. ]);
  284. $this->assertEquals('mark', end($entity->highlights)->author->name);
  285. $lastTag = end($entity->special_tags);
  286. $this->assertTrue($lastTag->highlighted);
  287. $this->assertEquals('2014-06-01 10:10:00', $lastTag->highlighted_time->format('Y-m-d H:i:s'));
  288. $this->assertEquals('mariano', $lastTag->author->name);
  289. }
  290. /**
  291. * Tests that no exceptions are generated becuase of ambiguous column names in queries
  292. * during a save operation
  293. *
  294. * @see https://github.com/cakephp/cakephp/issues/3803
  295. * @return void
  296. */
  297. public function testSaveWithCallbacks()
  298. {
  299. $this->loadFixtures('Articles', 'Authors');
  300. $articles = TableRegistry::get('Articles');
  301. $articles->belongsTo('Authors');
  302. $articles->eventManager()->attach(function ($event, $query) {
  303. return $query->contain('Authors');
  304. }, 'Model.beforeFind');
  305. $article = $articles->newEntity();
  306. $article->title = 'Foo';
  307. $article->body = 'Bar';
  308. $this->assertSame($article, $articles->save($article));
  309. }
  310. /**
  311. * Test that save() works with entities containing expressions
  312. * as properties.
  313. *
  314. * @return void
  315. */
  316. public function testSaveWithExpressionProperty()
  317. {
  318. $this->loadFixtures('Articles');
  319. $articles = TableRegistry::get('Articles');
  320. $article = $articles->newEntity();
  321. $article->title = new \Cake\Database\Expression\QueryExpression("SELECT 'jose'");
  322. $this->assertSame($article, $articles->save($article));
  323. }
  324. /**
  325. * Tests that whe saving deep associations for a belongsToMany property,
  326. * data is not removed becuase of excesive associations filtering.
  327. *
  328. * @see https://github.com/cakephp/cakephp/issues/4009
  329. * @return void
  330. */
  331. public function testBelongsToManyDeepSave2()
  332. {
  333. $this->loadFixtures('Articles', 'Tags', 'SpecialTags');
  334. $articles = TableRegistry::get('Articles');
  335. $articles->belongsToMany('Highlights', [
  336. 'className' => 'TestApp\Model\Table\TagsTable',
  337. 'foreignKey' => 'article_id',
  338. 'targetForeignKey' => 'tag_id',
  339. 'through' => 'SpecialTags',
  340. ]);
  341. $articles->Highlights->hasMany('TopArticles', [
  342. 'className' => 'TestApp\Model\Table\ArticlesTable',
  343. 'foreignKey' => 'author_id',
  344. ]);
  345. $entity = $articles->get(2, ['contain' => ['Highlights']]);
  346. $data = [
  347. 'highlights' => [
  348. [
  349. 'name' => 'New Special Tag',
  350. '_joinData' => [
  351. 'highlighted' => true,
  352. 'highlighted_time' => '2014-06-01 10:10:00',
  353. ],
  354. 'top_articles' => [
  355. ['title' => 'First top article'],
  356. ['title' => 'Second top article'],
  357. ]
  358. ]
  359. ]
  360. ];
  361. $options = [
  362. 'associated' => [
  363. 'Highlights._joinData', 'Highlights.TopArticles'
  364. ]
  365. ];
  366. $entity = $articles->patchEntity($entity, $data, $options);
  367. $articles->save($entity, $options);
  368. $entity = $articles->get(2, [
  369. 'contain' => [
  370. 'Highlights.TopArticles'
  371. ]
  372. ]);
  373. $highlights = $entity->highlights[0];
  374. $this->assertEquals('First top article', $highlights->top_articles[0]->title);
  375. $this->assertEquals('Second top article', $highlights->top_articles[1]->title);
  376. $this->assertEquals(
  377. new Time('2014-06-01 10:10:00'),
  378. $highlights->_joinData->highlighted_time
  379. );
  380. }
  381. /**
  382. * An integration test that spot checks that associations use the
  383. * correct alias names to generate queries.
  384. *
  385. * @return void
  386. */
  387. public function testPluginAssociationQueryGeneration()
  388. {
  389. $this->loadFixtures('Articles', 'Comments', 'Authors');
  390. Plugin::load('TestPlugin');
  391. $articles = TableRegistry::get('Articles');
  392. $articles->hasMany('TestPlugin.Comments');
  393. $articles->belongsTo('TestPlugin.Authors');
  394. $result = $articles->find()
  395. ->where(['Articles.id' => 2])
  396. ->contain(['Comments', 'Authors'])
  397. ->first();
  398. $this->assertNotEmpty(
  399. $result->comments[0]->id,
  400. 'No SQL error and comment exists.'
  401. );
  402. $this->assertNotEmpty(
  403. $result->author->id,
  404. 'No SQL error and author exists.'
  405. );
  406. }
  407. /**
  408. * Tests that loading associations having the same alias in the
  409. * joinable associations chain is not sensitive to the order in which
  410. * the associations are selected.
  411. *
  412. * @see https://github.com/cakephp/cakephp/issues/4454
  413. * @return void
  414. */
  415. public function testAssociationChainOrder()
  416. {
  417. $this->loadFixtures('Articles', 'Tags', 'ArticlesTags', 'Authors');
  418. $articles = TableRegistry::get('Articles');
  419. $articles->belongsTo('Authors');
  420. $articles->hasOne('ArticlesTags');
  421. $articlesTags = TableRegistry::get('ArticlesTags');
  422. $articlesTags->belongsTo('Authors', [
  423. 'foreignKey' => 'tag_id'
  424. ]);
  425. $resultA = $articles->find()
  426. ->contain(['ArticlesTags.Authors', 'Authors'])
  427. ->first();
  428. $resultB = $articles->find()
  429. ->contain(['Authors', 'ArticlesTags.Authors'])
  430. ->first();
  431. $this->assertEquals($resultA, $resultB);
  432. $this->assertNotEmpty($resultA->author);
  433. $this->assertNotEmpty($resultA->articles_tag->author);
  434. }
  435. /**
  436. * Test that offset/limit are elided from subquery loads.
  437. *
  438. * @return void
  439. */
  440. public function testAssociationSubQueryNoOffset()
  441. {
  442. $this->loadFixtures('Articles', 'Translates');
  443. $table = TableRegistry::get('Articles');
  444. $table->addBehavior('Translate', ['fields' => ['title', 'body']]);
  445. $table->locale('eng');
  446. $query = $table->find('translations')
  447. ->order(['Articles.id' => 'ASC'])
  448. ->limit(10)
  449. ->offset(1);
  450. $result = $query->toArray();
  451. $this->assertCount(2, $result);
  452. }
  453. /**
  454. * Tests that using the subquery strategy in a deep association returns the right results
  455. *
  456. * @see https://github.com/cakephp/cakephp/issues/4484
  457. * @return void
  458. */
  459. public function testDeepBelongsToManySubqueryStrategy()
  460. {
  461. $this->loadFixtures('Authors', 'Tags', 'Articles', 'ArticlesTags');
  462. $table = TableRegistry::get('Authors');
  463. $table->hasMany('Articles');
  464. $table->Articles->belongsToMany('Tags', [
  465. 'strategy' => 'subquery'
  466. ]);
  467. $result = $table->find()->contain(['Articles.Tags'])->toArray();
  468. $this->skipIf(count($result) == 0, 'No results, this test sometimes acts up on PHP 5.6');
  469. $this->assertEquals(
  470. ['tag1', 'tag3'],
  471. collection($result[2]->articles[0]->tags)->extract('name')->toArray()
  472. );
  473. }
  474. /**
  475. * Tests that using the subquery strategy in a deep association returns the right results
  476. *
  477. * @see https://github.com/cakephp/cakephp/issues/5769
  478. * @return void
  479. */
  480. public function testDeepBelongsToManySubqueryStrategy2()
  481. {
  482. $this->loadFixtures('Articles', 'Authors', 'Tags', 'Authors', 'AuthorsTags');
  483. $table = TableRegistry::get('Authors');
  484. $table->hasMany('Articles');
  485. $table->Articles->belongsToMany('Tags', [
  486. 'strategy' => 'subquery'
  487. ]);
  488. $table->belongsToMany('Tags', [
  489. 'strategy' => 'subquery',
  490. ]);
  491. $table->Articles->belongsTo('Authors');
  492. $result = $table->Articles->find()
  493. ->where(['Authors.id >' => 1])
  494. ->contain(['Authors.Tags'])
  495. ->toArray();
  496. $this->assertEquals(
  497. ['tag1', 'tag2'],
  498. collection($result[0]->author->tags)->extract('name')->toArray()
  499. );
  500. $this->assertEquals(3, $result[0]->author->id);
  501. }
  502. /**
  503. * Tests that finding on a table with a primary key other than `id` will work
  504. * seamlessly with either select or subquery.
  505. *
  506. * @see https://github.com/cakephp/cakephp/issues/6781
  507. * @return void
  508. */
  509. public function testDeepHasManyEitherStrategy()
  510. {
  511. $this->loadFixtures('Tags', 'FeaturedTags', 'TagsTranslations');
  512. $tags = TableRegistry::get('Tags');
  513. $this->skipIf(
  514. $tags->connection()->driver() instanceof \Cake\Database\Driver\Sqlserver,
  515. 'SQL server is temporarily weird in this test, will investigate later'
  516. );
  517. $tags = TableRegistry::get('Tags');
  518. $featuredTags = TableRegistry::get('FeaturedTags');
  519. $featuredTags->belongsTo('Tags');
  520. $tags->hasMany('TagsTranslations', [
  521. 'foreignKey' => 'id',
  522. 'strategy' => 'select'
  523. ]);
  524. $findViaSelect = $featuredTags
  525. ->find()
  526. ->where(['FeaturedTags.tag_id' => 2])
  527. ->contain('Tags.TagsTranslations')
  528. ->all();
  529. $tags->hasMany('TagsTranslations', [
  530. 'foreignKey' => 'id',
  531. 'strategy' => 'subquery'
  532. ]);
  533. $findViaSubquery = $featuredTags
  534. ->find()
  535. ->where(['FeaturedTags.tag_id' => 2])
  536. ->contain('Tags.TagsTranslations')
  537. ->all();
  538. $expected = [2 => 'tag 2 translated into en_us'];
  539. $this->assertEquals($expected, $findViaSelect->combine('tag_id', 'tag.tags_translations.0.name')->toArray());
  540. $this->assertEquals($expected, $findViaSubquery->combine('tag_id', 'tag.tags_translations.0.name')->toArray());
  541. }
  542. /**
  543. * Tests that getting the count of a query having containments return
  544. * the correct results
  545. *
  546. * @see https://github.com/cakephp/cakephp/issues/4511
  547. * @return void
  548. */
  549. public function testCountWithContain()
  550. {
  551. $this->loadFixtures('Articles', 'Authors');
  552. $table = TableRegistry::get('Articles');
  553. $table->belongsTo('Authors', ['joinType' => 'inner']);
  554. $count = $table
  555. ->find()
  556. ->contain(['Authors' => function ($q) {
  557. return $q->where(['Authors.id' => 1]);
  558. }])
  559. ->count();
  560. $this->assertEquals(2, $count);
  561. }
  562. /**
  563. * Tests that getting the count of a query with bind is correct
  564. *
  565. * @see https://github.com/cakephp/cakephp/issues/8466
  566. * @return void
  567. */
  568. public function testCountWithBind()
  569. {
  570. $this->loadFixtures('Articles');
  571. $table = TableRegistry::get('Articles');
  572. $query = $table
  573. ->find()
  574. ->select(['title', 'id'])
  575. ->where("title LIKE :val")
  576. ->group(['id', 'title'])
  577. ->bind(':val', '%Second%');
  578. $count = $query->count();
  579. $this->assertEquals(1, $count);
  580. }
  581. /**
  582. * Tests that bind in subqueries works.
  583. *
  584. * @return void
  585. */
  586. public function testSubqueryBind()
  587. {
  588. $this->loadFixtures('Articles');
  589. $table = TableRegistry::get('Articles');
  590. $sub = $table->find()
  591. ->select(['id'])
  592. ->where("title LIKE :val")
  593. ->bind(':val', 'Second %');
  594. $query = $table
  595. ->find()
  596. ->select(['title'])
  597. ->where(["id NOT IN" => $sub]);
  598. $result = $query->toArray();
  599. $this->assertCount(2, $result);
  600. $this->assertEquals('First Article', $result[0]->title);
  601. $this->assertEquals('Third Article', $result[1]->title);
  602. }
  603. /**
  604. * Test that deep containments don't generate empty entities for
  605. * intermediary relations.
  606. *
  607. * @return void
  608. */
  609. public function testContainNoEmptyAssociatedObjects()
  610. {
  611. $this->loadFixtures('Comments', 'Users', 'Articles');
  612. $comments = TableRegistry::get('Comments');
  613. $comments->belongsTo('Users');
  614. $users = TableRegistry::get('Users');
  615. $users->hasMany('Articles', [
  616. 'foreignKey' => 'author_id'
  617. ]);
  618. $comments->updateAll(['user_id' => 99], ['id' => 1]);
  619. $result = $comments->find()
  620. ->contain(['Users'])
  621. ->where(['Comments.id' => 1])
  622. ->first();
  623. $this->assertNull($result->user, 'No record should be null.');
  624. $result = $comments->find()
  625. ->contain(['Users', 'Users.Articles'])
  626. ->where(['Comments.id' => 1])
  627. ->first();
  628. $this->assertNull($result->user, 'No record should be null.');
  629. }
  630. /**
  631. * Tests that using a comparison expression inside an OR condition works
  632. *
  633. * @see https://github.com/cakephp/cakephp/issues/5081
  634. * @return void
  635. */
  636. public function testOrConditionsWithExpression()
  637. {
  638. $this->loadFixtures('Articles');
  639. $table = TableRegistry::get('Articles');
  640. $query = $table->find();
  641. $query->where([
  642. 'OR' => [
  643. new \Cake\Database\Expression\Comparison('id', 1, 'integer', '>'),
  644. new \Cake\Database\Expression\Comparison('id', 3, 'integer', '<')
  645. ]
  646. ]);
  647. $results = $query->toArray();
  648. $this->assertCount(3, $results);
  649. }
  650. /**
  651. * Tests that calling count on a query having a union works correctly
  652. *
  653. * @see https://github.com/cakephp/cakephp/issues/5107
  654. * @return void
  655. */
  656. public function testCountWithUnionQuery()
  657. {
  658. $this->loadFixtures('Articles');
  659. $table = TableRegistry::get('Articles');
  660. $query = $table->find()->where(['id' => 1]);
  661. $query2 = $table->find()->where(['id' => 2]);
  662. $query->union($query2);
  663. $this->assertEquals(2, $query->count());
  664. }
  665. /**
  666. * Integration test when selecting no fields on the primary table.
  667. *
  668. * @return void
  669. */
  670. public function testSelectNoFieldsOnPrimaryAlias()
  671. {
  672. $this->loadFixtures('Articles', 'Users');
  673. $table = TableRegistry::get('Articles');
  674. $table->belongsTo('Users');
  675. $query = $table->find()
  676. ->select(['Users__id' => 'id']);
  677. $results = $query->toArray();
  678. $this->assertCount(3, $results);
  679. }
  680. /**
  681. * Tests that calling first on the query results will not remove all other results
  682. * from the set.
  683. *
  684. * @return void
  685. */
  686. public function testFirstOnResultSet()
  687. {
  688. $this->loadFixtures('Articles');
  689. $results = TableRegistry::get('Articles')->find()->all();
  690. $this->assertEquals(3, $results->count());
  691. $this->assertNotNull($results->first());
  692. $this->assertCount(3, $results->toArray());
  693. }
  694. /**
  695. * Checks that matching and contain can be called for the same belongsTo association
  696. *
  697. * @see https://github.com/cakephp/cakephp/issues/5463
  698. * @return void
  699. */
  700. public function testFindMatchingAndContain()
  701. {
  702. $this->loadFixtures('Articles', 'Authors');
  703. $table = TableRegistry::get('Articles');
  704. $table->belongsTo('Authors');
  705. $article = $table->find()
  706. ->contain('Authors')
  707. ->matching('Authors', function ($q) {
  708. return $q->where(['Authors.id' => 1]);
  709. })
  710. ->first();
  711. $this->assertNotNull($article->author);
  712. $this->assertEquals($article->author, $article->_matchingData['Authors']);
  713. }
  714. /**
  715. * Checks that matching and contain can be called for the same belongsTo association
  716. *
  717. * @see https://github.com/cakephp/cakephp/issues/5463
  718. * @return void
  719. */
  720. public function testFindMatchingAndContainWithSubquery()
  721. {
  722. $this->loadFixtures('Articles', 'Authors', 'Tags', 'ArticlesTags');
  723. $table = TableRegistry::get('authors');
  724. $table->hasMany('articles', ['strategy' => 'subquery']);
  725. $table->articles->belongsToMany('tags');
  726. $result = $table->find()
  727. ->matching('articles.tags', function ($q) {
  728. return $q->where(['tags.id' => 2]);
  729. })
  730. ->contain('articles');
  731. $this->assertCount(2, $result->first()->articles);
  732. }
  733. /**
  734. * Tests that matching does not overwrite associations in contain
  735. *
  736. * @see https://github.com/cakephp/cakephp/issues/5584
  737. * @return void
  738. */
  739. public function testFindMatchingOverwrite()
  740. {
  741. $this->loadFixtures('Articles', 'Comments', 'Tags', 'ArticlesTags');
  742. $comments = TableRegistry::get('Comments');
  743. $comments->belongsTo('Articles');
  744. $articles = TableRegistry::get('Articles');
  745. $articles->belongsToMany('Tags');
  746. $result = $comments
  747. ->find()
  748. ->matching('Articles.Tags', function ($q) {
  749. return $q->where(['Tags.id' => 2]);
  750. })
  751. ->contain('Articles')
  752. ->first();
  753. $this->assertEquals(1, $result->id);
  754. $this->assertEquals(1, $result->_matchingData['Articles']->id);
  755. $this->assertEquals(2, $result->_matchingData['Tags']->id);
  756. $this->assertNotNull($result->article);
  757. $this->assertEquals($result->article, $result->_matchingData['Articles']);
  758. }
  759. /**
  760. * Tests that matching does not overwrite associations in contain
  761. *
  762. * @see https://github.com/cakephp/cakephp/issues/5584
  763. * @return void
  764. */
  765. public function testFindMatchingOverwrite2()
  766. {
  767. $this->loadFixtures('Articles', 'Comments', 'Tags', 'ArticlesTags', 'Authors');
  768. $comments = TableRegistry::get('Comments');
  769. $comments->belongsTo('Articles');
  770. $articles = TableRegistry::get('Articles');
  771. $articles->belongsTo('Authors');
  772. $articles->belongsToMany('Tags');
  773. $result = $comments
  774. ->find()
  775. ->matching('Articles.Tags', function ($q) {
  776. return $q->where(['Tags.id' => 2]);
  777. })
  778. ->contain('Articles.Authors')
  779. ->first();
  780. $this->assertNotNull($result->article->author);
  781. }
  782. /**
  783. * Tests that trying to contain an inexistent association
  784. * throws an exception and not a fatal error.
  785. *
  786. * @expectedException InvalidArgumentException
  787. * @return void
  788. */
  789. public function testQueryNotFatalError()
  790. {
  791. $this->loadFixtures('Comments');
  792. $comments = TableRegistry::get('Comments');
  793. $comments->find()->contain('Deprs')->all();
  794. }
  795. /**
  796. * Tests that using matching and contain on belongsTo associations
  797. * works correctly.
  798. *
  799. * @see https://github.com/cakephp/cakephp/issues/5721
  800. * @return void
  801. */
  802. public function testFindMatchingWithContain()
  803. {
  804. $this->loadFixtures('Articles', 'Comments', 'Users');
  805. $comments = TableRegistry::get('Comments');
  806. $comments->belongsTo('Articles');
  807. $comments->belongsTo('Users');
  808. $result = $comments->find()
  809. ->contain(['Articles', 'Users'])
  810. ->matching('Articles', function ($q) {
  811. return $q->where(['Articles.id >=' => 1]);
  812. })
  813. ->matching('Users', function ($q) {
  814. return $q->where(['Users.id >=' => 1]);
  815. })
  816. ->order(['Comments.id' => 'ASC'])
  817. ->first();
  818. $this->assertInstanceOf('Cake\ORM\Entity', $result->article);
  819. $this->assertInstanceOf('Cake\ORM\Entity', $result->user);
  820. $this->assertEquals(2, $result->user->id);
  821. $this->assertEquals(1, $result->article->id);
  822. }
  823. /**
  824. * Tests that HasMany associations don't use duplicate PK values.
  825. *
  826. * @return void
  827. */
  828. public function testHasManyEagerLoadingUniqueKey()
  829. {
  830. $this->loadFixtures('Articles', 'Tags', 'ArticlesTags');
  831. $table = TableRegistry::get('ArticlesTags');
  832. $table->belongsTo('Articles', [
  833. 'strategy' => 'select'
  834. ]);
  835. $result = $table->find()
  836. ->contain(['Articles' => function ($q) {
  837. $result = $q->sql();
  838. $this->assertNotContains(':c2', $result, 'Only 2 bindings as there are only 2 rows.');
  839. $this->assertNotContains(':c3', $result, 'Only 2 bindings as there are only 2 rows.');
  840. return $q;
  841. }])
  842. ->toArray();
  843. $this->assertNotEmpty($result[0]->article);
  844. }
  845. /**
  846. * Tests that using contain but selecting no fields from the association
  847. * does not trigger any errors and fetches the right results.
  848. *
  849. * @see https://github.com/cakephp/cakephp/issues/6214
  850. * @return void
  851. */
  852. public function testContainWithNoFields()
  853. {
  854. $this->loadFixtures('Comments', 'Users');
  855. $table = TableRegistry::get('Comments');
  856. $table->belongsTo('Users');
  857. $results = $table->find()
  858. ->select(['Comments.id', 'Comments.user_id'])
  859. ->contain(['Users'])
  860. ->where(['Users.id' => 1])
  861. ->combine('id', 'user_id');
  862. $this->assertEquals([3 => 1, 4 => 1, 5 => 1], $results->toArray());
  863. }
  864. /**
  865. * Tests that find() and contained associations using computed fields doesn't error out.
  866. *
  867. * @see https://github.com/cakephp/cakephp/issues/9326
  868. * @return void
  869. */
  870. public function testContainWithComputedField()
  871. {
  872. $this->loadFixtures('Comments', 'Users');
  873. $table = TableRegistry::get('Users');
  874. $table->hasMany('Comments');
  875. $query = $table->find()->contain([
  876. 'Comments' => function ($q) {
  877. return $q->select([
  878. 'concat' => $q->func()->concat(['red', 'blue']),
  879. 'user_id'
  880. ]);
  881. }])
  882. ->where(['Users.id' => 2]);
  883. $results = $query->toArray();
  884. $this->assertCount(1, $results);
  885. $this->assertEquals('redblue', $results[0]->comments[0]->concat);
  886. }
  887. /**
  888. * Tests that using matching and selecting no fields for that association
  889. * will no trigger any errors and fetch the right results
  890. *
  891. * @see https://github.com/cakephp/cakephp/issues/6223
  892. * @return void
  893. */
  894. public function testMatchingWithNoFields()
  895. {
  896. $this->loadFixtures('Comments', 'Users');
  897. $table = TableRegistry::get('Users');
  898. $table->hasMany('Comments');
  899. $results = $table->find()
  900. ->select(['Users.id'])
  901. ->matching('Comments', function ($q) {
  902. return $q->where(['Comments.id' => 1]);
  903. })
  904. ->extract('id')
  905. ->toList();
  906. $this->assertEquals([2], $results);
  907. }
  908. /**
  909. * Test that empty conditions in a matching clause don't cause errors.
  910. *
  911. * @return void
  912. */
  913. public function testMatchingEmptyQuery()
  914. {
  915. $this->loadFixtures('Articles', 'Tags', 'ArticlesTags');
  916. $table = TableRegistry::get('Articles');
  917. $table->belongsToMany('Tags');
  918. $rows = $table->find()
  919. ->matching('Tags', function ($q) {
  920. return $q->where([]);
  921. })
  922. ->all();
  923. $this->assertNotEmpty($rows);
  924. $rows = $table->find()
  925. ->matching('Tags', function ($q) {
  926. return $q->where(null);
  927. })
  928. ->all();
  929. $this->assertNotEmpty($rows);
  930. }
  931. /**
  932. * Tests that using a subquery as part of an expression will not make invalid SQL
  933. *
  934. * @return void
  935. */
  936. public function testSubqueryInSelectExpression()
  937. {
  938. $this->loadFixtures('Comments');
  939. $table = TableRegistry::get('Comments');
  940. $ratio = $table->find()
  941. ->select(function ($query) use ($table) {
  942. $allCommentsCount = $table->find()->select($query->func()->count('*'));
  943. $countToFloat = $query->newExpr([$query->func()->count('*'), '1.0'])->type('*');
  944. return [
  945. 'ratio' => $query
  946. ->newExpr($countToFloat)
  947. ->add($allCommentsCount)
  948. ->type('/')
  949. ];
  950. })
  951. ->where(['user_id' => 1])
  952. ->first()
  953. ->ratio;
  954. $this->assertEquals(0.5, $ratio);
  955. }
  956. /**
  957. * Tests calling last on an empty table
  958. *
  959. * @see https://github.com/cakephp/cakephp/issues/6683
  960. * @return void
  961. */
  962. public function testFindLastOnEmptyTable()
  963. {
  964. $this->loadFixtures('Comments');
  965. $table = TableRegistry::get('Comments');
  966. $table->deleteAll(['1 = 1']);
  967. $this->assertEquals(0, $table->find()->count());
  968. $this->assertNull($table->find()->last());
  969. }
  970. /**
  971. * Tests calling contain in a nested closure
  972. *
  973. * @see https://github.com/cakephp/cakephp/issues/7591
  974. * @return void
  975. */
  976. public function testContainInNestedClosure()
  977. {
  978. $this->loadFixtures('Comments', 'Articles', 'Authors', 'Tags', 'AuthorsTags');
  979. $table = TableRegistry::get('Comments');
  980. $table->belongsTo('Articles');
  981. $table->Articles->belongsTo('Authors');
  982. $table->Articles->Authors->belongsToMany('Tags');
  983. $query = $table->find()->where(['Comments.id' => 5])->contain(['Articles' => function ($q) {
  984. return $q->contain(['Authors' => function ($q) {
  985. return $q->contain('Tags');
  986. }]);
  987. }]);
  988. $this->assertCount(2, $query->first()->article->author->tags);
  989. }
  990. /**
  991. * Test that the typemaps used in function expressions
  992. * create the correct results.
  993. *
  994. * @return void
  995. */
  996. public function testTypemapInFunctions()
  997. {
  998. $this->loadFixtures('Comments');
  999. $table = TableRegistry::get('Comments');
  1000. $table->updateAll(['published' => null], ['1 = 1']);
  1001. $query = $table->find();
  1002. $query->select([
  1003. 'id',
  1004. 'coalesced' => $query->func()->coalesce(
  1005. ['published' => 'identifier', -1],
  1006. ['integer']
  1007. )
  1008. ]);
  1009. $result = $query->all()->first();
  1010. $this->assertSame(
  1011. -1,
  1012. $result['coalesced'],
  1013. 'Output values for functions should be casted'
  1014. );
  1015. }
  1016. /**
  1017. * Test that the typemaps used in function expressions
  1018. * create the correct results.
  1019. *
  1020. * @return void
  1021. */
  1022. public function testTypemapInFunctions2()
  1023. {
  1024. $this->loadFixtures('Comments');
  1025. $table = TableRegistry::get('Comments');
  1026. $query = $table->find();
  1027. $query->select([
  1028. 'max' => $query->func()->max('created', ['datetime'])
  1029. ]);
  1030. $result = $query->all()->first();
  1031. $this->assertEquals(new Time('2007-03-18 10:55:23'), $result['max']);
  1032. }
  1033. /**
  1034. * Test that contain queries map types correctly.
  1035. *
  1036. * @return void
  1037. */
  1038. public function testBooleanConditionsInContain()
  1039. {
  1040. $this->loadFixtures('Articles', 'Tags', 'SpecialTags');
  1041. $table = TableRegistry::get('Articles');
  1042. $table->belongsToMany('Tags', [
  1043. 'foreignKey' => 'article_id',
  1044. 'associationForeignKey' => 'tag_id',
  1045. 'through' => 'SpecialTags'
  1046. ]);
  1047. $query = $table->find()
  1048. ->contain(['Tags' => function ($q) {
  1049. return $q->where(['SpecialTags.highlighted_time >' => new Time('2014-06-01 00:00:00')]);
  1050. }])
  1051. ->where(['Articles.id' => 2]);
  1052. $result = $query->first();
  1053. $this->assertEquals(2, $result->id);
  1054. $this->assertNotEmpty($result->tags, 'Missing tags');
  1055. $this->assertNotEmpty($result->tags[0]->_joinData, 'Missing join data');
  1056. }
  1057. /**
  1058. * Test that contain/matching/innerJoinWith/leftJoinWith/notMatching
  1059. * queries map types correctly.
  1060. *
  1061. * @return void
  1062. */
  1063. public function testComplexTypesInJoinedWhere()
  1064. {
  1065. $this->loadFixtures('Comments', 'Users', 'Articles', 'Tags', 'ArticlesTags');
  1066. $table = TableRegistry::get('Users');
  1067. $table->hasOne('Comments', [
  1068. 'foreignKey' => 'user_id',
  1069. ]);
  1070. $query = $table->find()
  1071. ->contain('Comments')
  1072. ->where([
  1073. 'Comments.updated >' => new \DateTime('2007-03-18 10:55:00')
  1074. ]);
  1075. $result = $query->first();
  1076. $this->assertNotEmpty($result);
  1077. $this->assertInstanceOf('Cake\I18n\Time', $result->comment->updated);
  1078. $query = $table->find()
  1079. ->matching('Comments')
  1080. ->where([
  1081. 'Comments.updated >' => new \DateTime('2007-03-18 10:55:00')
  1082. ]);
  1083. $result = $query->first();
  1084. $this->assertNotEmpty($result);
  1085. $this->assertInstanceOf('Cake\I18n\Time', $result->_matchingData['Comments']->updated);
  1086. $query = $table->find()
  1087. ->innerJoinWith('Comments')
  1088. ->where([
  1089. 'Comments.updated >' => new \DateTime('2007-03-18 10:55:00')
  1090. ]);
  1091. $result = $query->first();
  1092. $this->assertNotEmpty($result);
  1093. $this->assertInstanceOf('Cake\I18n\Time', $result->updated);
  1094. $query = $table->find()
  1095. ->leftJoinWith('Comments')
  1096. ->where([
  1097. 'Comments.updated >' => new \DateTime('2007-03-18 10:55:00')
  1098. ]);
  1099. $result = $query->first();
  1100. $this->assertNotEmpty($result);
  1101. $this->assertInstanceOf('Cake\I18n\Time', $result->updated);
  1102. $Tags = TableRegistry::get('Tags');
  1103. $Tags->belongsToMany('Articles');
  1104. $query = $Tags->find()
  1105. ->notMatching('Articles', function ($q) {
  1106. return $q ->where(['ArticlesTags.tag_id !=' => 3 ]);
  1107. })
  1108. ->where([
  1109. 'Tags.created <' => new \DateTime('2016-01-02 00:00:00')
  1110. ]);
  1111. $result = $query->first();
  1112. $this->assertNotEmpty($result);
  1113. $this->assertEquals(3, $result->id);
  1114. $this->assertInstanceOf('Cake\I18n\Time', $result->created);
  1115. }
  1116. /**
  1117. * Test that nested contain/matching/innerJoinWith/leftJoinWith
  1118. * queries map types correctly.
  1119. *
  1120. * @return void
  1121. */
  1122. public function testComplexNestedTypesInJoinedWhere()
  1123. {
  1124. $this->loadFixtures('Comments', 'Users', 'Articles');
  1125. $table = TableRegistry::get('Users');
  1126. $table->hasOne('Comments', [
  1127. 'foreignKey' => 'user_id',
  1128. ]);
  1129. $table->Comments->belongsTo('Articles');
  1130. $table->Comments->Articles->belongsTo('Authors', [
  1131. 'className' => 'Users',
  1132. 'foreignKey' => 'author_id'
  1133. ]);
  1134. $query = $table->find()
  1135. ->contain('Comments.Articles.Authors')
  1136. ->where([
  1137. 'Authors.created >' => new \DateTime('2007-03-17 01:16:00')
  1138. ]);
  1139. $result = $query->first();
  1140. $this->assertNotEmpty($result);
  1141. $this->assertInstanceOf('Cake\I18n\Time', $result->comment->article->author->updated);
  1142. $query = $table->find()
  1143. ->matching('Comments.Articles.Authors')
  1144. ->where([
  1145. 'Authors.created >' => new \DateTime('2007-03-17 01:16:00')
  1146. ]);
  1147. $result = $query->first();
  1148. $this->assertNotEmpty($result);
  1149. $this->assertInstanceOf('Cake\I18n\Time', $result->_matchingData['Authors']->updated);
  1150. $query = $table->find()
  1151. ->innerJoinWith('Comments.Articles.Authors')
  1152. ->where([
  1153. 'Authors.created >' => new \DateTime('2007-03-17 01:16:00')
  1154. ]);
  1155. $result = $query->first();
  1156. $this->assertNotEmpty($result);
  1157. $this->assertInstanceOf('Cake\I18n\Time', $result->updated);
  1158. $query = $table->find()
  1159. ->leftJoinWith('Comments.Articles.Authors')
  1160. ->where([
  1161. 'Authors.created >' => new \DateTime('2007-03-17 01:16:00')
  1162. ]);
  1163. $result = $query->first();
  1164. $this->assertNotEmpty($result);
  1165. $this->assertInstanceOf('Cake\I18n\Time', $result->updated);
  1166. }
  1167. /**
  1168. * Tests that it is possible to contain to fetch
  1169. * associations off of a junction table.
  1170. *
  1171. * @return void
  1172. */
  1173. public function testBelongsToManyJoinDataAssociation()
  1174. {
  1175. $this->loadFixtures('Authors', 'Articles', 'Tags', 'SpecialTags');
  1176. $articles = TableRegistry::get('Articles');
  1177. $tags = TableRegistry::get('Tags');
  1178. $tags->hasMany('SpecialTags');
  1179. $specialTags = TableRegistry::get('SpecialTags');
  1180. $specialTags->belongsTo('Authors');
  1181. $specialTags->belongsTo('Articles');
  1182. $specialTags->belongsTo('Tags');
  1183. $articles->belongsToMany('Tags', [
  1184. 'through' => $specialTags
  1185. ]);
  1186. $query = $articles->find()
  1187. ->contain(['Tags', 'Tags.SpecialTags.Authors'])
  1188. ->where(['Articles.id' => 1]);
  1189. $result = $query->first();
  1190. $this->assertNotEmpty($result->tags, 'Missing tags');
  1191. $this->assertNotEmpty($result->tags[0], 'Missing first tag');
  1192. $this->assertNotEmpty($result->tags[0]->_joinData, 'Missing _joinData');
  1193. $this->assertNotEmpty($result->tags[0]->special_tags[0]->author, 'Missing author on _joinData');
  1194. }
  1195. /**
  1196. * Tests that it is possible to use matching with dot notation
  1197. * even when part of the part of the path in the dot notation is
  1198. * shared for two different calls
  1199. *
  1200. * @return void
  1201. */
  1202. public function testDotNotationNotOverride()
  1203. {
  1204. $this->loadFixtures('Comments', 'Articles', 'Tags', 'Authors', 'SpecialTags');
  1205. $table = TableRegistry::get('Comments');
  1206. $articles = $table->belongsTo('Articles');
  1207. $specialTags = $articles->hasMany('SpecialTags');
  1208. $specialTags->belongsTo('Authors');
  1209. $specialTags->belongsTo('Tags');
  1210. $results = $table
  1211. ->find()
  1212. ->select(['name' => 'Authors.name', 'tag' => 'Tags.name'])
  1213. ->matching('Articles.SpecialTags.Tags')
  1214. ->matching('Articles.SpecialTags.Authors', function ($q) {
  1215. return $q->where(['Authors.id' => 2]);
  1216. })
  1217. ->distinct()
  1218. ->hydrate(false)
  1219. ->toArray();
  1220. $this->assertEquals([['name' => 'nate', 'tag' => 'tag1']], $results);
  1221. }
  1222. /**
  1223. * Test expression based ordering with unions.
  1224. *
  1225. * @return void
  1226. */
  1227. public function testComplexOrderWithUnion()
  1228. {
  1229. $this->loadFixtures('Comments');
  1230. $table = TableRegistry::get('Comments');
  1231. $query = $table->find();
  1232. $inner = $table->find()
  1233. ->select(['content' => 'comment'])
  1234. ->where(['id >' => 3]);
  1235. $inner2 = $table->find()
  1236. ->select(['content' => 'comment'])
  1237. ->where(['id <' => 3]);
  1238. $order = $query->func()->concat(['content' => 'literal', 'test']);
  1239. $query->select(['inside.content'])
  1240. ->from(['inside' => $inner->unionAll($inner2)])
  1241. ->orderAsc($order);
  1242. $results = $query->toArray();
  1243. $this->assertCount(5, $results);
  1244. }
  1245. /**
  1246. * Test that associations that are loaded with subqueries
  1247. * do not cause errors when the subquery has a limit & order clause.
  1248. *
  1249. * @return void
  1250. */
  1251. public function testEagerLoadOrderAndSubquery()
  1252. {
  1253. $this->loadFixtures('Articles', 'Comments');
  1254. $table = TableRegistry::get('Articles');
  1255. $table->hasMany('Comments', [
  1256. 'strategy' => 'subquery'
  1257. ]);
  1258. $query = $table->find()
  1259. ->select(['score' => 100])
  1260. ->autoFields(true)
  1261. ->contain(['Comments'])
  1262. ->limit(5)
  1263. ->order(['score' => 'desc']);
  1264. $result = $query->all();
  1265. $this->assertCount(3, $result);
  1266. }
  1267. /**
  1268. * Tests that decorating the results does not result in a memory leak
  1269. *
  1270. * @return void
  1271. */
  1272. public function testFormatResultsMemoryLeak()
  1273. {
  1274. $this->loadFixtures('Articles', 'Authors', 'Tags', 'ArticlesTags');
  1275. $this->skipIf(env('CODECOVERAGE') == 1, 'Running coverage this causes this tests to fail sometimes.');
  1276. $table = TableRegistry::get('Articles');
  1277. $table->belongsTo('Authors');
  1278. $table->belongsToMany('Tags');
  1279. gc_collect_cycles();
  1280. $memory = memory_get_usage() / 1024 / 1024;
  1281. foreach (range(1, 3) as $time) {
  1282. $table->find()
  1283. ->contain(['Authors', 'Tags'])
  1284. ->formatResults(function ($results) {
  1285. return $results;
  1286. })
  1287. ->all();
  1288. }
  1289. gc_collect_cycles();
  1290. $endMemory = memory_get_usage() / 1024 / 1024;
  1291. $this->assertWithinRange($endMemory, $memory, 1.25, 'Memory leak in ResultSet');
  1292. }
  1293. /**
  1294. * Tests that having bound placeholders in the order clause does not result
  1295. * in an error when trying to count a query.
  1296. *
  1297. * @return void
  1298. */
  1299. public function testCountWithComplexOrderBy()
  1300. {
  1301. $this->loadFixtures('Articles');
  1302. $table = TableRegistry::get('Articles');
  1303. $query = $table->find();
  1304. $query->orderDesc($query->newExpr()->addCase(
  1305. [$query->newExpr()->add(['id' => 3])],
  1306. [1, 0]
  1307. ));
  1308. $query->order(['title' => 'desc']);
  1309. // Executing the normal query before getting the count
  1310. $query->all();
  1311. $this->assertEquals(3, $query->count());
  1312. $table = TableRegistry::get('Articles');
  1313. $query = $table->find();
  1314. $query->orderDesc($query->newExpr()->addCase(
  1315. [$query->newExpr()->add(['id' => 3])],
  1316. [1, 0]
  1317. ));
  1318. $query->orderDesc($query->newExpr()->add(['id' => 3]));
  1319. // Not executing the query first, just getting the count
  1320. $this->assertEquals(3, $query->count());
  1321. }
  1322. /**
  1323. * Tests that the now() function expression can be used in the
  1324. * where clause of a query
  1325. *
  1326. * @see https://github.com/cakephp/cakephp/issues/7943
  1327. * @return void
  1328. */
  1329. public function testFunctionInWhereClause()
  1330. {
  1331. $this->loadFixtures('Comments');
  1332. $table = TableRegistry::get('Comments');
  1333. $table->updateAll(['updated' => Time::tomorrow()], ['id' => 6]);
  1334. $query = $table->find();
  1335. $result = $query->where(['updated >' => $query->func()->now('datetime')])->first();
  1336. $this->assertSame(6, $result->id);
  1337. }
  1338. /**
  1339. * Tests that `notMatching()` can be used on `belongsToMany`
  1340. * associations without passing a query builder callback.
  1341. *
  1342. * @return void
  1343. */
  1344. public function testNotMatchingForBelongsToManyWithoutQueryBuilder()
  1345. {
  1346. $this->loadFixtures('Articles', 'Tags', 'ArticlesTags');
  1347. $Articles = TableRegistry::get('Articles');
  1348. $Articles->belongsToMany('Tags');
  1349. $result = $Articles->find('list')->notMatching('Tags')->toArray();
  1350. $expected = [
  1351. 3 => 'Third Article'
  1352. ];
  1353. $this->assertEquals($expected, $result);
  1354. }
  1355. }