QueryRegressionTest.php 54 KB

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