QueryRegressionTest.php 57 KB

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