QueryRegressionTest.php 65 KB

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