HasManyTest.php 47 KB

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