QueryRegressionTest.php 58 KB

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