PageRenderTime 54ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 1ms

/tests/TestCase/ORM/Association/HasManyTest.php

http://github.com/cakephp/cakephp
PHP | 1525 lines | 1081 code | 197 blank | 247 comment | 7 complexity | 2172f32634904e3e5c442e74145fef5f MD5 | raw file
Possible License(s): JSON

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  5. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  6. *
  7. * Licensed under The MIT License
  8. * For full copyright and license information, please see the LICENSE.txt
  9. * Redistributions of files must retain the above copyright notice.
  10. *
  11. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  12. * @link https://cakephp.org CakePHP(tm) Project
  13. * @since 3.0.0
  14. * @license https://opensource.org/licenses/mit-license.php MIT License
  15. */
  16. namespace Cake\Test\TestCase\ORM\Association;
  17. use Cake\Database\Driver\Sqlserver;
  18. use Cake\Database\Expression\OrderByExpression;
  19. use Cake\Database\Expression\QueryExpression;
  20. use Cake\Database\Expression\TupleComparison;
  21. use Cake\Database\IdentifierQuoter;
  22. use Cake\Database\StatementInterface;
  23. use Cake\Database\TypeMap;
  24. use Cake\Datasource\ConnectionManager;
  25. use Cake\ORM\Association;
  26. use Cake\ORM\Association\HasMany;
  27. use Cake\ORM\Entity;
  28. use Cake\ORM\ResultSet;
  29. use Cake\TestSuite\TestCase;
  30. use Closure;
  31. use InvalidArgumentException;
  32. /**
  33. * Tests HasMany class
  34. */
  35. class HasManyTest extends TestCase
  36. {
  37. /**
  38. * Fixtures
  39. *
  40. * @var array<string>
  41. */
  42. protected $fixtures = [
  43. 'core.Comments',
  44. 'core.Articles',
  45. 'core.Tags',
  46. 'core.Authors',
  47. 'core.Users',
  48. 'core.ArticlesTags',
  49. ];
  50. /**
  51. * @var \Cake\ORM\Table|\PHPUnit\Framework\MockObject\MockObject
  52. */
  53. protected $author;
  54. /**
  55. * @var \Cake\ORM\Table|\PHPUnit\Framework\MockObject\MockObject
  56. */
  57. protected $article;
  58. /**
  59. * @var \Cake\Database\TypeMap
  60. */
  61. protected $articlesTypeMap;
  62. /**
  63. * @var bool
  64. */
  65. protected $autoQuote;
  66. /**
  67. * Set up
  68. */
  69. public function setUp(): void
  70. {
  71. parent::setUp();
  72. $this->setAppNamespace('TestApp');
  73. $this->author = $this->getTableLocator()->get('Authors', [
  74. 'schema' => [
  75. 'id' => ['type' => 'integer'],
  76. 'name' => ['type' => 'string'],
  77. '_constraints' => [
  78. 'primary' => ['type' => 'primary', 'columns' => ['id']],
  79. ],
  80. ],
  81. ]);
  82. $connection = ConnectionManager::get('test');
  83. $this->article = $this->getMockBuilder('Cake\ORM\Table')
  84. ->onlyMethods(['find', 'deleteAll', 'delete'])
  85. ->setConstructorArgs([['alias' => 'Articles', 'table' => 'articles', 'connection' => $connection]])
  86. ->getMock();
  87. $this->article->setSchema([
  88. 'id' => ['type' => 'integer'],
  89. 'title' => ['type' => 'string'],
  90. 'author_id' => ['type' => 'integer'],
  91. '_constraints' => [
  92. 'primary' => ['type' => 'primary', 'columns' => ['id']],
  93. ],
  94. ]);
  95. $this->articlesTypeMap = new TypeMap([
  96. 'Articles.id' => 'integer',
  97. 'id' => 'integer',
  98. 'Articles.title' => 'string',
  99. 'title' => 'string',
  100. 'Articles.author_id' => 'integer',
  101. 'author_id' => 'integer',
  102. 'Articles__id' => 'integer',
  103. 'Articles__title' => 'string',
  104. 'Articles__author_id' => 'integer',
  105. ]);
  106. $this->autoQuote = $connection->getDriver()->isAutoQuotingEnabled();
  107. }
  108. /**
  109. * Tests that foreignKey() returns the correct configured value
  110. */
  111. public function testSetForeignKey(): void
  112. {
  113. $assoc = new HasMany('Articles', [
  114. 'sourceTable' => $this->author,
  115. ]);
  116. $this->assertSame('author_id', $assoc->getForeignKey());
  117. $this->assertSame($assoc, $assoc->setForeignKey('another_key'));
  118. $this->assertSame('another_key', $assoc->getForeignKey());
  119. }
  120. /**
  121. * Test that foreignKey generation ignores database names in target table.
  122. */
  123. public function testForeignKeyIgnoreDatabaseName(): void
  124. {
  125. $this->author->setTable('schema.authors');
  126. $assoc = new HasMany('Articles', [
  127. 'sourceTable' => $this->author,
  128. ]);
  129. $this->assertSame('author_id', $assoc->getForeignKey());
  130. }
  131. /**
  132. * Tests that the association reports it can be joined
  133. */
  134. public function testCanBeJoined(): void
  135. {
  136. $assoc = new HasMany('Test');
  137. $this->assertFalse($assoc->canBeJoined());
  138. }
  139. /**
  140. * Tests setSort() method
  141. */
  142. public function testSetSort(): void
  143. {
  144. $assoc = new HasMany('Test');
  145. $this->assertNull($assoc->getSort());
  146. $assoc->setSort(['id' => 'ASC']);
  147. $this->assertEquals(['id' => 'ASC'], $assoc->getSort());
  148. }
  149. /**
  150. * Tests requiresKeys() method
  151. */
  152. public function testRequiresKeys(): void
  153. {
  154. $assoc = new HasMany('Test');
  155. $this->assertTrue($assoc->requiresKeys());
  156. $assoc->setStrategy(HasMany::STRATEGY_SUBQUERY);
  157. $this->assertFalse($assoc->requiresKeys());
  158. $assoc->setStrategy(HasMany::STRATEGY_SELECT);
  159. $this->assertTrue($assoc->requiresKeys());
  160. }
  161. /**
  162. * Tests that HasMany can't use the join strategy
  163. */
  164. public function testStrategyFailure(): void
  165. {
  166. $this->expectException(InvalidArgumentException::class);
  167. $this->expectExceptionMessage('Invalid strategy "join" was provided');
  168. $assoc = new HasMany('Test');
  169. $assoc->setStrategy(HasMany::STRATEGY_JOIN);
  170. }
  171. /**
  172. * Test the eager loader method with no extra options
  173. */
  174. public function testEagerLoader(): void
  175. {
  176. $config = [
  177. 'sourceTable' => $this->author,
  178. 'targetTable' => $this->article,
  179. 'strategy' => 'select',
  180. ];
  181. $association = new HasMany('Articles', $config);
  182. $query = $this->article->query();
  183. $this->article->method('find')
  184. ->with('all')
  185. ->will($this->returnValue($query));
  186. $keys = [1, 2, 3, 4];
  187. $callable = $association->eagerLoader(compact('keys', 'query'));
  188. $row = ['Authors__id' => 1];
  189. $result = $callable($row);
  190. $this->assertArrayHasKey('Articles', $result);
  191. $this->assertSame($row['Authors__id'], $result['Articles'][0]->author_id);
  192. $this->assertSame($row['Authors__id'], $result['Articles'][1]->author_id);
  193. $row = ['Authors__id' => 2];
  194. $result = $callable($row);
  195. $this->assertArrayNotHasKey('Articles', $result);
  196. $row = ['Authors__id' => 3];
  197. $result = $callable($row);
  198. $this->assertArrayHasKey('Articles', $result);
  199. $this->assertSame($row['Authors__id'], $result['Articles'][0]->author_id);
  200. $row = ['Authors__id' => 4];
  201. $result = $callable($row);
  202. $this->assertArrayNotHasKey('Articles', $result);
  203. }
  204. /**
  205. * Test the eager loader method with default query clauses
  206. */
  207. public function testEagerLoaderWithDefaults(): void
  208. {
  209. $config = [
  210. 'sourceTable' => $this->author,
  211. 'targetTable' => $this->article,
  212. 'conditions' => ['Articles.published' => 'Y'],
  213. 'sort' => ['id' => 'ASC'],
  214. 'strategy' => 'select',
  215. ];
  216. $association = new HasMany('Articles', $config);
  217. $keys = [1, 2, 3, 4];
  218. $query = $this->article->query();
  219. $this->article->method('find')
  220. ->with('all')
  221. ->will($this->returnValue($query));
  222. $association->eagerLoader(compact('keys', 'query'));
  223. $expected = new QueryExpression(
  224. ['Articles.published' => 'Y', 'Articles.author_id IN' => $keys],
  225. $this->articlesTypeMap
  226. );
  227. $this->assertWhereClause($expected, $query);
  228. $expected = new OrderByExpression(['id' => 'ASC']);
  229. $this->assertOrderClause($expected, $query);
  230. }
  231. /**
  232. * Test the eager loader method with overridden query clauses
  233. */
  234. public function testEagerLoaderWithOverrides(): void
  235. {
  236. $config = [
  237. 'sourceTable' => $this->author,
  238. 'targetTable' => $this->article,
  239. 'conditions' => ['Articles.published' => 'Y'],
  240. 'sort' => ['id' => 'ASC'],
  241. 'strategy' => 'select',
  242. ];
  243. $this->article->hasMany('Comments');
  244. $association = new HasMany('Articles', $config);
  245. $keys = [1, 2, 3, 4];
  246. /** @var \Cake\ORM\Query $query */
  247. $query = $this->article->query();
  248. $query->addDefaultTypes($this->article->Comments->getSource());
  249. $this->article->method('find')
  250. ->with('all')
  251. ->will($this->returnValue($query));
  252. $association->eagerLoader([
  253. 'conditions' => ['Articles.id !=' => 3],
  254. 'sort' => ['title' => 'DESC'],
  255. 'fields' => ['id', 'title', 'author_id'],
  256. 'contain' => ['Comments' => ['fields' => ['comment', 'article_id']]],
  257. 'keys' => $keys,
  258. 'query' => $query,
  259. ]);
  260. $expected = [
  261. 'Articles__id' => 'Articles.id',
  262. 'Articles__title' => 'Articles.title',
  263. 'Articles__author_id' => 'Articles.author_id',
  264. ];
  265. $this->assertSelectClause($expected, $query);
  266. $expected = new QueryExpression(
  267. [
  268. 'Articles.published' => 'Y',
  269. 'Articles.id !=' => 3,
  270. 'Articles.author_id IN' => $keys,
  271. ],
  272. $query->getTypeMap()
  273. );
  274. $this->assertWhereClause($expected, $query);
  275. $expected = new OrderByExpression(['title' => 'DESC']);
  276. $this->assertOrderClause($expected, $query);
  277. $this->assertArrayHasKey('Comments', $query->getContain());
  278. }
  279. /**
  280. * Test that failing to add the foreignKey to the list of fields will throw an
  281. * exception
  282. */
  283. public function testEagerLoaderFieldsException(): void
  284. {
  285. $this->expectException(InvalidArgumentException::class);
  286. $this->expectExceptionMessage('You are required to select the "Articles.author_id"');
  287. $config = [
  288. 'sourceTable' => $this->author,
  289. 'targetTable' => $this->article,
  290. 'strategy' => 'select',
  291. ];
  292. $association = new HasMany('Articles', $config);
  293. $keys = [1, 2, 3, 4];
  294. $query = $this->article->query();
  295. $this->article->method('find')
  296. ->with('all')
  297. ->will($this->returnValue($query));
  298. $association->eagerLoader([
  299. 'fields' => ['id', 'title'],
  300. 'keys' => $keys,
  301. 'query' => $query,
  302. ]);
  303. }
  304. /**
  305. * Tests that eager loader accepts a queryBuilder option
  306. */
  307. public function testEagerLoaderWithQueryBuilder(): void
  308. {
  309. $config = [
  310. 'sourceTable' => $this->author,
  311. 'targetTable' => $this->article,
  312. 'strategy' => 'select',
  313. ];
  314. $association = new HasMany('Articles', $config);
  315. $keys = [1, 2, 3, 4];
  316. /** @var \Cake\ORM\Query $query */
  317. $query = $this->article->query();
  318. $this->article->method('find')
  319. ->with('all')
  320. ->will($this->returnValue($query));
  321. $queryBuilder = function ($query) {
  322. return $query->select(['author_id'])->join('comments')->where(['comments.id' => 1]);
  323. };
  324. $association->eagerLoader(compact('keys', 'query', 'queryBuilder'));
  325. $expected = [
  326. 'Articles__author_id' => 'Articles.author_id',
  327. ];
  328. $this->assertSelectClause($expected, $query);
  329. $expected = [
  330. [
  331. 'type' => 'INNER',
  332. 'alias' => null,
  333. 'table' => 'comments',
  334. 'conditions' => new QueryExpression([], $query->getTypeMap()),
  335. ],
  336. ];
  337. $this->assertJoin($expected, $query);
  338. $expected = new QueryExpression(
  339. [
  340. 'Articles.author_id IN' => $keys,
  341. 'comments.id' => 1,
  342. ],
  343. $query->getTypeMap()
  344. );
  345. $this->assertWhereClause($expected, $query);
  346. }
  347. /**
  348. * Test the eager loader method with no extra options
  349. */
  350. public function testEagerLoaderMultipleKeys(): void
  351. {
  352. $config = [
  353. 'sourceTable' => $this->author,
  354. 'targetTable' => $this->article,
  355. 'strategy' => 'select',
  356. 'foreignKey' => ['author_id', 'site_id'],
  357. ];
  358. $this->author->setPrimaryKey(['id', 'site_id']);
  359. $association = new HasMany('Articles', $config);
  360. $keys = [[1, 10], [2, 20], [3, 30], [4, 40]];
  361. $query = $this->getMockBuilder('Cake\ORM\Query')
  362. ->onlyMethods(['all', 'andWhere', 'getRepository'])
  363. ->setConstructorArgs([ConnectionManager::get('test'), $this->article])
  364. ->getMock();
  365. $query->method('getRepository')
  366. ->will($this->returnValue($this->article));
  367. $this->article->method('find')
  368. ->with('all')
  369. ->will($this->returnValue($query));
  370. $stmt = $this->getMockBuilder(StatementInterface::class)->getMock();
  371. $results = new ResultSet($query, $stmt);
  372. $results->unserialize(serialize([
  373. ['id' => 1, 'title' => 'article 1', 'author_id' => 2, 'site_id' => 10],
  374. ['id' => 2, 'title' => 'article 2', 'author_id' => 1, 'site_id' => 20],
  375. ]));
  376. $query->method('all')
  377. ->will($this->returnValue($results));
  378. $tuple = new TupleComparison(
  379. ['Articles.author_id', 'Articles.site_id'],
  380. $keys,
  381. ['integer'],
  382. 'IN'
  383. );
  384. $query->expects($this->once())->method('andWhere')
  385. ->with($tuple)
  386. ->will($this->returnSelf());
  387. $callable = $association->eagerLoader(compact('keys', 'query'));
  388. $row = ['Authors__id' => 2, 'Authors__site_id' => 10, 'username' => 'author 1'];
  389. $result = $callable($row);
  390. $row['Articles'] = [
  391. ['id' => 1, 'title' => 'article 1', 'author_id' => 2, 'site_id' => 10],
  392. ];
  393. $this->assertEquals($row, $result);
  394. $row = ['Authors__id' => 1, 'username' => 'author 2', 'Authors__site_id' => 20];
  395. $result = $callable($row);
  396. $row['Articles'] = [
  397. ['id' => 2, 'title' => 'article 2', 'author_id' => 1, 'site_id' => 20],
  398. ];
  399. $this->assertEquals($row, $result);
  400. }
  401. /**
  402. * Test that not selecting join keys fails with an error
  403. */
  404. public function testEagerloaderNoForeignKeys(): void
  405. {
  406. $authors = $this->getTableLocator()->get('Authors');
  407. $authors->hasMany('Articles');
  408. $this->expectException(InvalidArgumentException::class);
  409. $this->expectExceptionMessage('Unable to load `Articles` association. Ensure foreign key in `Authors`');
  410. $query = $authors->find()
  411. ->select(['Authors.name'])
  412. ->where(['Authors.id' => 1])
  413. ->contain('Articles');
  414. $query->first();
  415. }
  416. /**
  417. * Test cascading deletes.
  418. */
  419. public function testCascadeDelete(): void
  420. {
  421. $articles = $this->getTableLocator()->get('Articles');
  422. $config = [
  423. 'dependent' => true,
  424. 'sourceTable' => $this->author,
  425. 'targetTable' => $articles,
  426. 'conditions' => ['Articles.published' => 'Y'],
  427. ];
  428. $association = new HasMany('Articles', $config);
  429. $entity = new Entity(['id' => 1, 'name' => 'PHP']);
  430. $this->assertTrue($association->cascadeDelete($entity));
  431. $published = $articles
  432. ->find('published')
  433. ->where([
  434. 'published' => 'Y',
  435. 'author_id' => 1,
  436. ]);
  437. $this->assertCount(0, $published->all());
  438. }
  439. /**
  440. * Test cascading deletes with a finder
  441. */
  442. public function testCascadeDeleteFinder(): void
  443. {
  444. $articles = $this->getTableLocator()->get('Articles');
  445. $config = [
  446. 'dependent' => true,
  447. 'sourceTable' => $this->author,
  448. 'targetTable' => $articles,
  449. 'finder' => 'published',
  450. ];
  451. // Exclude one record from the association finder
  452. $articles->updateAll(
  453. ['published' => 'N'],
  454. ['author_id' => 1, 'title' => 'First Article']
  455. );
  456. $association = new HasMany('Articles', $config);
  457. $entity = new Entity(['id' => 1, 'name' => 'PHP']);
  458. $this->assertTrue($association->cascadeDelete($entity));
  459. $published = $articles->find('published')->where(['author_id' => 1]);
  460. $this->assertCount(0, $published->all(), 'Associated records should be removed');
  461. $all = $articles->find()->where(['author_id' => 1]);
  462. $this->assertCount(1, $all->all(), 'Record not in association finder should remain');
  463. }
  464. /**
  465. * Test cascading delete with has many.
  466. */
  467. public function testCascadeDeleteCallbacks(): void
  468. {
  469. $articles = $this->getTableLocator()->get('Articles');
  470. $config = [
  471. 'dependent' => true,
  472. 'sourceTable' => $this->author,
  473. 'targetTable' => $articles,
  474. 'conditions' => ['Articles.published' => 'Y'],
  475. 'cascadeCallbacks' => true,
  476. ];
  477. $association = new HasMany('Articles', $config);
  478. $author = new Entity(['id' => 1, 'name' => 'mark']);
  479. $this->assertTrue($association->cascadeDelete($author));
  480. $query = $articles->query()->where(['author_id' => 1]);
  481. $this->assertSame(0, $query->count(), 'Cleared related rows');
  482. $query = $articles->query()->where(['author_id' => 3]);
  483. $this->assertSame(1, $query->count(), 'other records left behind');
  484. }
  485. /**
  486. * Test cascading delete with a rule preventing deletion
  487. */
  488. public function testCascadeDeleteCallbacksRuleFailure(): void
  489. {
  490. $articles = $this->getTableLocator()->get('Articles');
  491. $config = [
  492. 'dependent' => true,
  493. 'sourceTable' => $this->author,
  494. 'targetTable' => $articles,
  495. 'cascadeCallbacks' => true,
  496. ];
  497. $association = new HasMany('Articles', $config);
  498. $articles = $association->getTarget();
  499. $articles->getEventManager()->on('Model.buildRules', function ($event, $rules): void {
  500. $rules->addDelete(function () {
  501. return false;
  502. });
  503. });
  504. $author = new Entity(['id' => 1, 'name' => 'mark']);
  505. $this->assertFalse($association->cascadeDelete($author));
  506. $matching = $articles->find()
  507. ->where(['Articles.author_id' => $author->id])
  508. ->all();
  509. $this->assertGreaterThan(0, count($matching));
  510. }
  511. /**
  512. * Test that saveAssociated() ignores non entity values.
  513. */
  514. public function testSaveAssociatedOnlyEntities(): void
  515. {
  516. $mock = $this->getMockBuilder('Cake\ORM\Table')
  517. ->addMethods(['saveAssociated'])
  518. ->disableOriginalConstructor()
  519. ->getMock();
  520. $config = [
  521. 'sourceTable' => $this->author,
  522. 'targetTable' => $mock,
  523. ];
  524. $entity = new Entity([
  525. 'username' => 'Mark',
  526. 'email' => 'mark@example.com',
  527. 'articles' => [
  528. ['title' => 'First Post'],
  529. new Entity(['title' => 'Second Post']),
  530. ],
  531. ]);
  532. $mock->expects($this->never())
  533. ->method('saveAssociated');
  534. $association = new HasMany('Articles', $config);
  535. $association->saveAssociated($entity);
  536. }
  537. /**
  538. * Tests that property is being set using the constructor options.
  539. */
  540. public function testPropertyOption(): void
  541. {
  542. $config = ['propertyName' => 'thing_placeholder'];
  543. $association = new HasMany('Thing', $config);
  544. $this->assertSame('thing_placeholder', $association->getProperty());
  545. }
  546. /**
  547. * Test that plugin names are omitted from property()
  548. */
  549. public function testPropertyNoPlugin(): void
  550. {
  551. $mock = $this->getMockBuilder('Cake\ORM\Table')
  552. ->disableOriginalConstructor()
  553. ->getMock();
  554. $config = [
  555. 'sourceTable' => $this->author,
  556. 'targetTable' => $mock,
  557. ];
  558. $association = new HasMany('Contacts.Addresses', $config);
  559. $this->assertSame('addresses', $association->getProperty());
  560. }
  561. /**
  562. * Test that the ValueBinder is reset when using strategy = Association::STRATEGY_SUBQUERY
  563. */
  564. public function testValueBinderUpdateOnSubQueryStrategy(): void
  565. {
  566. $Authors = $this->getTableLocator()->get('Authors');
  567. $Authors->hasMany('Articles', [
  568. 'strategy' => Association::STRATEGY_SUBQUERY,
  569. ]);
  570. $query = $Authors->find();
  571. $authorsAndArticles = $query
  572. ->select([
  573. 'id',
  574. 'slug' => $query->func()->concat([
  575. '---',
  576. 'name' => 'identifier',
  577. ]),
  578. ])
  579. ->contain('Articles')
  580. ->where(['name' => 'mariano'])
  581. ->first();
  582. $this->assertCount(2, $authorsAndArticles->get('articles'));
  583. }
  584. /**
  585. * Tests using subquery strategy when parent query
  586. * that contains limit without order.
  587. */
  588. public function testSubqueryWithLimit()
  589. {
  590. $Authors = $this->getTableLocator()->get('Authors');
  591. $Authors->hasMany('Articles', [
  592. 'strategy' => Association::STRATEGY_SUBQUERY,
  593. ]);
  594. $query = $Authors->find();
  595. $result = $query
  596. ->contain('Articles')
  597. ->first();
  598. if (in_array($result->name, ['mariano', 'larry'])) {
  599. $this->assertNotEmpty($result->articles);
  600. } else {
  601. $this->assertEmpty($result->articles);
  602. }
  603. }
  604. /**
  605. * Tests using subquery strategy when parent query
  606. * that contains limit with order.
  607. */
  608. public function testSubqueryWithLimitAndOrder()
  609. {
  610. $this->skipIf(ConnectionManager::get('test')->getDriver() instanceof Sqlserver, 'Sql Server does not support ORDER BY on field not in GROUP BY');
  611. $Authors = $this->getTableLocator()->get('Authors');
  612. $Authors->hasMany('Articles', [
  613. 'strategy' => Association::STRATEGY_SUBQUERY,
  614. ]);
  615. $query = $Authors->find();
  616. $result = $query
  617. ->contain('Articles')
  618. ->order(['name' => 'ASC'])
  619. ->limit(2)
  620. ->toArray();
  621. $this->assertCount(0, $result[0]->articles);
  622. $this->assertCount(1, $result[1]->articles);
  623. }
  624. /**
  625. * Assertion method for order by clause contents.
  626. *
  627. * @param array $expected The expected join clause.
  628. * @param \Cake\ORM\Query $query The query to check.
  629. */
  630. protected function assertJoin($expected, $query): void
  631. {
  632. if ($this->autoQuote) {
  633. $driver = $query->getConnection()->getDriver();
  634. $quoter = new IdentifierQuoter($driver);
  635. foreach ($expected as &$join) {
  636. $join['table'] = $driver->quoteIdentifier($join['table']);
  637. if ($join['conditions']) {
  638. $quoter->quoteExpression($join['conditions']);
  639. }
  640. }
  641. }
  642. $this->assertEquals($expected, array_values($query->clause('join')));
  643. }
  644. /**
  645. * Assertion method for where clause contents.
  646. *
  647. * @param \Cake\Database\QueryExpression $expected The expected where clause.
  648. * @param \Cake\ORM\Query $query The query to check.
  649. */
  650. protected function assertWhereClause($expected, $query): void
  651. {
  652. if ($this->autoQuote) {
  653. $quoter = new IdentifierQuoter($query->getConnection()->getDriver());
  654. $expected->traverse(Closure::fromCallable([$quoter, 'quoteExpression']));
  655. }
  656. $this->assertEquals($expected, $query->clause('where'));
  657. }
  658. /**
  659. * Assertion method for order by clause contents.
  660. *
  661. * @param \Cake\Database\QueryExpression $expected The expected where clause.
  662. * @param \Cake\ORM\Query $query The query to check.
  663. */
  664. protected function assertOrderClause($expected, $query): void
  665. {
  666. if ($this->autoQuote) {
  667. $quoter = new IdentifierQuoter($query->getConnection()->getDriver());
  668. $quoter->quoteExpression($expected);
  669. }
  670. $this->assertEquals($expected, $query->clause('order'));
  671. }
  672. /**
  673. * Assertion method for select clause contents.
  674. *
  675. * @param array $expected Array of expected fields.
  676. * @param \Cake\ORM\Query $query The query to check.
  677. */
  678. protected function assertSelectClause($expected, $query): void
  679. {
  680. if ($this->autoQuote) {
  681. $connection = $query->getConnection();
  682. foreach ($expected as $key => $value) {
  683. $expected[$connection->quoteIdentifier($key)] = $connection->quoteIdentifier($value);
  684. unset($expected[$key]);
  685. }
  686. }
  687. $this->assertEquals($expected, $query->clause('select'));
  688. }
  689. /**
  690. * Tests that unlinking calls the right methods
  691. */
  692. public function testUnlinkSuccess(): void
  693. {
  694. $articles = $this->getTableLocator()->get('Articles');
  695. $assoc = $this->author->hasMany('Articles', [
  696. 'sourceTable' => $this->author,
  697. 'targetTable' => $articles,
  698. ]);
  699. $entity = $this->author->get(1, ['contain' => 'Articles']);
  700. $initial = $entity->articles;
  701. $this->assertCount(2, $initial);
  702. $assoc->unlink($entity, $entity->articles);
  703. $this->assertEmpty($entity->get('articles'), 'Property should be empty');
  704. $new = $this->author->get(2, ['contain' => 'Articles']);
  705. $this->assertCount(0, $new->articles, 'DB should be clean');
  706. $this->assertSame(4, $this->author->find()->count(), 'Authors should still exist');
  707. $this->assertSame(3, $articles->find()->count(), 'Articles should still exist');
  708. }
  709. /**
  710. * Tests that unlink with an empty array does nothing
  711. */
  712. public function testUnlinkWithEmptyArray(): void
  713. {
  714. $articles = $this->getTableLocator()->get('Articles');
  715. $assoc = $this->author->hasMany('Articles', [
  716. 'sourceTable' => $this->author,
  717. 'targetTable' => $articles,
  718. ]);
  719. $entity = $this->author->get(1, ['contain' => 'Articles']);
  720. $initial = $entity->articles;
  721. $this->assertCount(2, $initial);
  722. $assoc->unlink($entity, []);
  723. $new = $this->author->get(1, ['contain' => 'Articles']);
  724. $this->assertCount(2, $new->articles, 'Articles should remain linked');
  725. $this->assertSame(4, $this->author->find()->count(), 'Authors should still exist');
  726. $this->assertSame(3, $articles->find()->count(), 'Articles should still exist');
  727. }
  728. /**
  729. * Tests that link only uses a single database transaction
  730. */
  731. public function testLinkUsesSingleTransaction(): void
  732. {
  733. $articles = $this->getTableLocator()->get('Articles');
  734. $assoc = $this->author->hasMany('Articles', [
  735. 'sourceTable' => $this->author,
  736. 'targetTable' => $articles,
  737. ]);
  738. // Ensure author in fixture has zero associated articles
  739. $entity = $this->author->get(2, ['contain' => 'Articles']);
  740. $initial = $entity->articles;
  741. $this->assertCount(0, $initial);
  742. // Ensure that after each model is saved, we are still within a transaction.
  743. $listenerAfterSave = function ($e, $entity, $options) use ($articles): void {
  744. $this->assertTrue(
  745. $articles->getConnection()->inTransaction(),
  746. 'Multiple transactions used to save associated models.'
  747. );
  748. };
  749. $articles->getEventManager()->on('Model.afterSave', $listenerAfterSave);
  750. $options = ['atomic' => false];
  751. $assoc->link($entity, $articles->find('all')->toArray(), $options);
  752. // Ensure that link was successful.
  753. $new = $this->author->get(2, ['contain' => 'Articles']);
  754. $this->assertCount(3, $new->articles);
  755. }
  756. /**
  757. * Test that saveAssociated() fails on non-empty, non-iterable value
  758. */
  759. public function testSaveAssociatedNotEmptyNotIterable(): void
  760. {
  761. $this->expectException(InvalidArgumentException::class);
  762. $this->expectExceptionMessage('Could not save comments, it cannot be traversed');
  763. $articles = $this->getTableLocator()->get('Articles');
  764. $association = $articles->hasMany('Comments', [
  765. 'saveStrategy' => HasMany::SAVE_APPEND,
  766. ]);
  767. $entity = $articles->newEmptyEntity();
  768. $entity->set('comments', 'oh noes');
  769. $association->saveAssociated($entity);
  770. }
  771. /**
  772. * Data provider for empty values.
  773. *
  774. * @return array
  775. */
  776. public function emptySetDataProvider(): array
  777. {
  778. return [
  779. [''],
  780. [false],
  781. [null],
  782. [[]],
  783. ];
  784. }
  785. /**
  786. * Test that saving empty sets with the `append` strategy does not
  787. * affect the associated records for not yet persisted parent entities.
  788. *
  789. * @dataProvider emptySetDataProvider
  790. * @param mixed $value Empty value.
  791. */
  792. public function testSaveAssociatedEmptySetWithAppendStrategyDoesNotAffectAssociatedRecordsOnCreate($value): void
  793. {
  794. $articles = $this->getTableLocator()->get('Articles');
  795. $association = $articles->hasMany('Comments', [
  796. 'saveStrategy' => HasMany::SAVE_APPEND,
  797. ]);
  798. $comments = $association->find();
  799. $this->assertNotEmpty($comments);
  800. $entity = $articles->newEmptyEntity();
  801. $entity->set('comments', $value);
  802. $this->assertSame($entity, $association->saveAssociated($entity));
  803. $this->assertEquals($value, $entity->get('comments'));
  804. $this->assertEquals($comments, $association->find());
  805. }
  806. /**
  807. * Test that saving empty sets with the `append` strategy does not
  808. * affect the associated records for already persisted parent entities.
  809. *
  810. * @dataProvider emptySetDataProvider
  811. * @param mixed $value Empty value.
  812. */
  813. public function testSaveAssociatedEmptySetWithAppendStrategyDoesNotAffectAssociatedRecordsOnUpdate($value): void
  814. {
  815. $articles = $this->getTableLocator()->get('Articles');
  816. $association = $articles->hasMany('Comments', [
  817. 'saveStrategy' => HasMany::SAVE_APPEND,
  818. ]);
  819. $entity = $articles->get(1, [
  820. 'contain' => ['Comments'],
  821. ]);
  822. $comments = $entity->get('comments');
  823. $this->assertNotEmpty($comments);
  824. $entity->set('comments', $value);
  825. $this->assertSame($entity, $association->saveAssociated($entity));
  826. $this->assertEquals($value, $entity->get('comments'));
  827. $entity = $articles->get(1, [
  828. 'contain' => ['Comments'],
  829. ]);
  830. $this->assertEquals($comments, $entity->get('comments'));
  831. }
  832. /**
  833. * Test that saving empty sets with the `replace` strategy does not
  834. * affect the associated records for not yet persisted parent entities.
  835. *
  836. * @dataProvider emptySetDataProvider
  837. * @param mixed $value Empty value.
  838. */
  839. public function testSaveAssociatedEmptySetWithReplaceStrategyDoesNotAffectAssociatedRecordsOnCreate($value): void
  840. {
  841. $articles = $this->getTableLocator()->get('Articles');
  842. $association = $articles->hasMany('Comments', [
  843. 'saveStrategy' => HasMany::SAVE_REPLACE,
  844. ]);
  845. $comments = $association->find();
  846. $this->assertNotEmpty($comments);
  847. $entity = $articles->newEmptyEntity();
  848. $entity->set('comments', $value);
  849. $this->assertSame($entity, $association->saveAssociated($entity));
  850. $this->assertEquals($value, $entity->get('comments'));
  851. $this->assertEquals($comments, $association->find());
  852. }
  853. /**
  854. * Test that saving empty sets with the `replace` strategy does remove
  855. * the associated records for already persisted parent entities.
  856. *
  857. * @dataProvider emptySetDataProvider
  858. * @param mixed $value Empty value.
  859. */
  860. public function testSaveAssociatedEmptySetWithReplaceStrategyRemovesAssociatedRecordsOnUpdate($value): void
  861. {
  862. $articles = $this->getTableLocator()->get('Articles');
  863. $association = $articles->hasMany('Comments', [
  864. 'saveStrategy' => HasMany::SAVE_REPLACE,
  865. ]);
  866. $entity = $articles->get(1, [
  867. 'contain' => ['Comments'],
  868. ]);
  869. $comments = $entity->get('comments');
  870. $this->assertNotEmpty($comments);
  871. $entity->set('comments', $value);
  872. $this->assertSame($entity, $association->saveAssociated($entity));
  873. $this->assertEquals([], $entity->get('comments'));
  874. $entity = $articles->get(1, [
  875. 'contain' => ['Comments'],
  876. ]);
  877. $this->assertEmpty($entity->get('comments'));
  878. }
  879. /**
  880. * Test that the associated entities are not saved when there's any rule
  881. * that fail on them and the errors are correctly set on the original entity.
  882. */
  883. public function testSaveAssociatedWithFailedRuleOnAssociated(): void
  884. {
  885. $articles = $this->getTableLocator()->get('Articles');
  886. $articles->hasMany('Comments');
  887. $comments = $this->getTableLocator()->get('Comments');
  888. $comments->belongsTo('Users');
  889. $rules = $comments->rulesChecker();
  890. $rules->add($rules->existsIn('user_id', 'Users'));
  891. $article = $articles->newEntity([
  892. 'title' => 'Bakeries are sky rocketing',
  893. 'body' => 'All because of cake',
  894. 'comments' => [
  895. [
  896. 'user_id' => 1,
  897. 'comment' => 'That is true!',
  898. ],
  899. [
  900. 'user_id' => 999, // This rule will fail because the user doesn't exist
  901. 'comment' => 'Of course',
  902. ],
  903. ],
  904. ], ['associated' => ['Comments']]);
  905. $this->assertFalse($article->hasErrors());
  906. $this->assertFalse($articles->save($article, ['associated' => ['Comments']]));
  907. $this->assertTrue($article->hasErrors());
  908. $this->assertFalse($article->comments[0]->hasErrors());
  909. $this->assertTrue($article->comments[1]->hasErrors());
  910. $this->assertNotEmpty($article->comments[1]->getErrors());
  911. $expected = [
  912. 'user_id' => [
  913. '_existsIn' => __('This value does not exist'),
  914. ],
  915. ];
  916. $this->assertEquals($expected, $article->comments[1]->getErrors());
  917. }
  918. /**
  919. * Tests that providing an invalid strategy throws an exception
  920. */
  921. public function testInvalidSaveStrategy(): void
  922. {
  923. $this->expectException(InvalidArgumentException::class);
  924. $articles = $this->getTableLocator()->get('Articles');
  925. $association = $articles->hasMany('Comments');
  926. $association->setSaveStrategy('anotherThing');
  927. }
  928. /**
  929. * Tests saveStrategy
  930. */
  931. public function testSetSaveStrategy(): void
  932. {
  933. $articles = $this->getTableLocator()->get('Articles');
  934. $association = $articles->hasMany('Comments');
  935. $this->assertSame($association, $association->setSaveStrategy(HasMany::SAVE_REPLACE));
  936. $this->assertSame(HasMany::SAVE_REPLACE, $association->getSaveStrategy());
  937. }
  938. /**
  939. * Test that save works with replace saveStrategy and are not deleted once they are not null
  940. */
  941. public function testSaveReplaceSaveStrategy(): void
  942. {
  943. $authors = $this->getTableLocator()->get('Authors');
  944. $authors->hasMany('Articles', ['saveStrategy' => HasMany::SAVE_REPLACE]);
  945. $entity = $authors->newEntity([
  946. 'name' => 'mylux',
  947. 'articles' => [
  948. ['title' => 'One Random Post', 'body' => 'The cake is not a lie'],
  949. ['title' => 'Another Random Post', 'body' => 'The cake is nice'],
  950. ['title' => 'One more random post', 'body' => 'The cake is forever'],
  951. ],
  952. ], ['associated' => ['Articles']]);
  953. $entity = $authors->save($entity, ['associated' => ['Articles']]);
  954. $sizeArticles = count($entity->articles);
  955. $this->assertSame($sizeArticles, $authors->Articles->find('all')->where(['author_id' => $entity['id']])->count());
  956. $articleId = $entity->articles[0]->id;
  957. unset($entity->articles[0]);
  958. $entity->setDirty('articles', true);
  959. $authors->save($entity, ['associated' => ['Articles']]);
  960. $this->assertSame($sizeArticles - 1, $authors->Articles->find('all')->where(['author_id' => $entity['id']])->count());
  961. $this->assertTrue($authors->Articles->exists(['id' => $articleId]));
  962. }
  963. /**
  964. * Test that save works with replace saveStrategy conditions
  965. */
  966. public function testSaveReplaceSaveStrategyClosureConditions(): void
  967. {
  968. $authors = $this->getTableLocator()->get('Authors');
  969. $authors->hasMany('Articles')
  970. ->setDependent(true)
  971. ->setSaveStrategy('replace')
  972. ->setConditions(function () {
  973. return ['published' => 'Y'];
  974. });
  975. $entity = $authors->newEntity([
  976. 'name' => 'mylux',
  977. 'articles' => [
  978. ['title' => 'Not matching conditions', 'body' => '', 'published' => 'N'],
  979. ['title' => 'Random Post', 'body' => 'The cake is nice', 'published' => 'Y'],
  980. ['title' => 'Another Random Post', 'body' => 'The cake is yummy', 'published' => 'Y'],
  981. ['title' => 'One more random post', 'body' => 'The cake is forever', 'published' => 'Y'],
  982. ],
  983. ], ['associated' => ['Articles']]);
  984. $entity = $authors->save($entity, ['associated' => ['Articles']]);
  985. $sizeArticles = count($entity->articles);
  986. // Should be one fewer because of conditions.
  987. $this->assertSame($sizeArticles - 1, $authors->Articles->find('all')->where(['author_id' => $entity['id']])->count());
  988. $articleId = $entity->articles[0]->id;
  989. unset($entity->articles[0], $entity->articles[1]);
  990. $entity->setDirty('articles', true);
  991. $authors->save($entity, ['associated' => ['Articles']]);
  992. $this->assertSame($sizeArticles - 2, $authors->Articles->find('all')->where(['author_id' => $entity['id']])->count());
  993. // Should still exist because it doesn't match the association conditions.
  994. $articles = $this->getTableLocator()->get('Articles');
  995. $this->assertTrue($articles->exists(['id' => $articleId]));
  996. }
  997. /**
  998. * Test that save works with replace saveStrategy, replacing the already persisted entities even if no new entities are passed
  999. */
  1000. public function testSaveReplaceSaveStrategyNotAdding(): void
  1001. {
  1002. $authors = $this->getTableLocator()->get('Authors');
  1003. $authors->hasMany('Articles', ['saveStrategy' => 'replace']);
  1004. $entity = $authors->newEntity([
  1005. 'name' => 'mylux',
  1006. 'articles' => [
  1007. ['title' => 'One Random Post', 'body' => 'The cake is not a lie'],
  1008. ['title' => 'Another Random Post', 'body' => 'The cake is nice'],
  1009. ['title' => 'One more random post', 'body' => 'The cake is forever'],
  1010. ],
  1011. ], ['associated' => ['Articles']]);
  1012. $entity = $authors->save($entity, ['associated' => ['Articles']]);
  1013. $sizeArticles = count($entity->articles);
  1014. $this->assertCount($sizeArticles, $authors->Articles->find('all')->where(['author_id' => $entity['id']]));
  1015. $entity->set('articles', []);
  1016. $entity = $authors->save($entity, ['associated' => ['Articles']]);
  1017. $this->assertCount(0, $authors->Articles->find('all')->where(['author_id' => $entity['id']]));
  1018. }
  1019. /**
  1020. * Test that save works with append saveStrategy not deleting or setting null anything
  1021. */
  1022. public function testSaveAppendSaveStrategy(): void
  1023. {
  1024. $authors = $this->getTableLocator()->get('Authors');
  1025. $authors->hasMany('Articles', ['saveStrategy' => 'append']);
  1026. $entity = $authors->newEntity([
  1027. 'name' => 'mylux',
  1028. 'articles' => [
  1029. ['title' => 'One Random Post', 'body' => 'The cake is not a lie'],
  1030. ['title' => 'Another Random Post', 'body' => 'The cake is nice'],
  1031. ['title' => 'One more random post', 'body' => 'The cake is forever'],
  1032. ],
  1033. ], ['associated' => ['Articles']]);
  1034. $entity = $authors->save($entity, ['associated' => ['Articles']]);
  1035. $sizeArticles = count($entity->articles);
  1036. $this->assertSame($sizeArticles, $authors->Articles->find('all')->where(['author_id' => $entity['id']])->count());
  1037. $articleId = $entity->articles[0]->id;
  1038. unset($entity->articles[0]);
  1039. $entity->setDirty('articles', true);
  1040. $authors->save($entity, ['associated' => ['Articles']]);
  1041. $this->assertSame($sizeArticles, $authors->Articles->find('all')->where(['author_id' => $entity['id']])->count());
  1042. $this->assertTrue($authors->Articles->exists(['id' => $articleId]));
  1043. }
  1044. /**
  1045. * Test that save has append as the default save strategy
  1046. */
  1047. public function testSaveDefaultSaveStrategy(): void
  1048. {
  1049. $authors = $this->getTableLocator()->get('Authors');
  1050. $authors->hasMany('Articles', ['saveStrategy' => HasMany::SAVE_APPEND]);
  1051. $this->assertSame(HasMany::SAVE_APPEND, $authors->getAssociation('articles')->getSaveStrategy());
  1052. }
  1053. /**
  1054. * Test that the associated entities are unlinked and deleted when they are dependent
  1055. */
  1056. public function testSaveReplaceSaveStrategyDependent(): void
  1057. {
  1058. $authors = $this->getTableLocator()->get('Authors');
  1059. $authors->hasMany('Articles', ['saveStrategy' => HasMany::SAVE_REPLACE, 'dependent' => true]);
  1060. $entity = $authors->newEntity([
  1061. 'name' => 'mylux',
  1062. 'articles' => [
  1063. ['title' => 'One Random Post', 'body' => 'The cake is not a lie'],
  1064. ['title' => 'Another Random Post', 'body' => 'The cake is nice'],
  1065. ['title' => 'One more random post', 'body' => 'The cake is forever'],
  1066. ],
  1067. ], ['associated' => ['Articles']]);
  1068. $entity = $authors->save($entity, ['associated' => ['Articles']]);
  1069. $sizeArticles = count($entity->articles);
  1070. $this->assertSame($sizeArticles, $authors->Articles->find('all')->where(['author_id' => $entity['id']])->count());
  1071. $articleId = $entity->articles[0]->id;
  1072. unset($entity->articles[0]);
  1073. $entity->setDirty('articles', true);
  1074. $authors->save($entity, ['associated' => ['Articles']]);
  1075. $this->assertSame($sizeArticles - 1, $authors->Articles->find('all')->where(['author_id' => $entity['id']])->count());
  1076. $this->assertFalse($authors->Articles->exists(['id' => $articleId]));
  1077. }
  1078. /**
  1079. * Test that the associated entities are unlinked and deleted when they are dependent
  1080. * when associated entities array is indexed by string keys
  1081. */
  1082. public function testSaveReplaceSaveStrategyDependentWithStringKeys(): void
  1083. {
  1084. $authors = $this->getTableLocator()->get('Authors');
  1085. $authors->hasMany('Articles', ['saveStrategy' => HasMany::SAVE_REPLACE, 'dependent' => true]);
  1086. $entity = $authors->newEntity([
  1087. 'name' => 'mylux',
  1088. 'articles' => [
  1089. ['title' => 'One Random Post', 'body' => 'The cake is not a lie'],
  1090. ['title' => 'Another Random Post', 'body' => 'The cake is nice'],
  1091. ['title' => 'One more random post', 'body' => 'The cake is forever'],
  1092. ],
  1093. ], ['associated' => ['Articles']]);
  1094. $entity = $authors->saveOrFail($entity, ['associated' => ['Articles']]);
  1095. $sizeArticles = count($entity->articles);
  1096. $this->assertSame($sizeArticles, $authors->Articles->find('all')->where(['author_id' => $entity['id']])->count());
  1097. $articleId = $entity->articles[0]->id;
  1098. $entity->articles = [
  1099. 'one' => $entity->articles[1],
  1100. 'two' => $entity->articles[2],
  1101. ];
  1102. $authors->saveOrFail($entity, ['associated' => ['Articles']]);
  1103. $this->assertSame($sizeArticles - 1, $authors->Articles->find('all')->where(['author_id' => $entity['id']])->count());
  1104. $this->assertFalse($authors->Articles->exists(['id' => $articleId]));
  1105. }
  1106. /**
  1107. * Test that the associated entities are unlinked and deleted when they are dependent
  1108. *
  1109. * In the future this should change and apply the finder.
  1110. */
  1111. public function testSaveReplaceSaveStrategyDependentWithConditions(): void
  1112. {
  1113. $this->getTableLocator()->clear();
  1114. $this->setAppNamespace('TestApp');
  1115. $authors = $this->getTableLocator()->get('Authors');
  1116. $authors->hasMany('Articles', [
  1117. 'finder' => 'published',
  1118. 'saveStrategy' => HasMany::SAVE_REPLACE,
  1119. 'dependent' => true,
  1120. ]);
  1121. $articles = $authors->Articles->getTarget();
  1122. // Remove an article from the association finder scope
  1123. $articles->updateAll(['published' => 'N'], ['author_id' => 1, 'title' => 'Third Article']);
  1124. $entity = $authors->get(1, ['contain' => ['Articles']]);
  1125. $data = [
  1126. 'name' => 'updated',
  1127. 'articles' => [
  1128. ['title' => 'New First', 'body' => 'New First', 'published' => 'Y'],
  1129. ],
  1130. ];
  1131. $entity = $authors->patchEntity($entity, $data, ['associated' => ['Articles']]);
  1132. $entity = $authors->save($entity, ['associated' => ['Articles']]);
  1133. // Should only have one article left as we 'replaced' the others.
  1134. $this->assertCount(1, $entity->articles);
  1135. // No additional records in db.
  1136. $this->assertCount(
  1137. 1,
  1138. $authors->Articles->find()->where(['author_id' => 1])->toArray()
  1139. );
  1140. $others = $articles->find('all')
  1141. ->where(['Articles.author_id' => 1, 'published' => 'N'])
  1142. ->orderAsc('title')
  1143. ->toArray();
  1144. $this->assertCount(
  1145. 1,
  1146. $others,
  1147. 'Record not matching association condition should stay'
  1148. );
  1149. $this->assertSame('Third Article', $others[0]->title);
  1150. }
  1151. /**
  1152. * Test that the associated entities are unlinked and deleted when they have a not nullable foreign key
  1153. */
  1154. public function testSaveReplaceSaveStrategyNotNullable(): void
  1155. {
  1156. $articles = $this->getTableLocator()->get('Articles');
  1157. $articles->hasMany('Comments', ['saveStrategy' => HasMany::SAVE_REPLACE]);
  1158. $article = $articles->newEntity([
  1159. 'title' => 'Bakeries are sky rocketing',
  1160. 'body' => 'All because of cake',
  1161. 'comments' => [
  1162. [
  1163. 'user_id' => 1,
  1164. 'comment' => 'That is true!',
  1165. ],
  1166. [
  1167. 'user_id' => 2,
  1168. 'comment' => 'Of course',
  1169. ],
  1170. ],
  1171. ], ['associated' => ['Comments']]);
  1172. $article = $articles->save($article, ['associated' => ['Comments']]);
  1173. $commentId = $article->comments[0]->id;
  1174. $sizeComments = count($article->comments);
  1175. $this->assertSame($sizeComments, $articles->Comments->find('all')->where(['article_id' => $article->id])->count());
  1176. $this->assertTrue($articles->Comments->exists(['id' => $commentId]));
  1177. unset($article->comments[0]);
  1178. $article->setDirty('comments', true);
  1179. $article = $articles->save($article, ['associated' => ['Comments']]);
  1180. $this->assertSame($sizeComments - 1, $articles->Comments->find('all')->where(['article_id' => $article->id])->count());
  1181. $this->assertFalse($articles->Comments->exists(['id' => $commentId]));
  1182. }
  1183. /**
  1184. * Test that the associated entities are unlinked and deleted when they have a not nullable foreign key
  1185. */
  1186. public function testSaveReplaceSaveStrategyAdding(): void
  1187. {
  1188. $articles = $this->getTableLocator()->get('Articles');
  1189. $articles->hasMany('Comments', ['saveStrategy' => HasMany::SAVE_REPLACE]);
  1190. $article = $articles->newEntity([
  1191. 'title' => 'Bakeries are sky rocketing',
  1192. 'body' => 'All because of cake',
  1193. 'comments' => [
  1194. [
  1195. 'user_id' => 1,
  1196. 'comment' => 'That is true!',
  1197. ],
  1198. [
  1199. 'user_id' => 2,
  1200. 'comment' => 'Of course',
  1201. ],
  1202. ],
  1203. ], ['associated' => ['Comments']]);
  1204. $article = $articles->save($article, ['associated' => ['Comments']]);
  1205. $commentId = $article->comments[0]->id;
  1206. $sizeComments = count($article->comments);
  1207. $articleId = $article->id;
  1208. $this->assertSame($sizeComments, $articles->Comments->find('all')->where(['article_id' => $article->id])->count());
  1209. $this->assertTrue($articles->Comments->exists(['id' => $commentId]));
  1210. unset($article->comments[0]);
  1211. $article->comments[] = $articles->Comments->newEntity([
  1212. 'user_id' => 1,
  1213. 'comment' => 'new comment',

Large files files are truncated, but you can click here to view the full file