QueryRegressionTest.php 56 KB

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