QueryRegressionTest.php 58 KB

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