Browse Source

HasMany fails to save if associated entities array is indexed by string keys

Edgaras Janušauskas 7 years ago
parent
commit
12f89a6541
2 changed files with 38 additions and 1 deletions
  1. 1 1
      src/ORM/Association/HasMany.php
  2. 37 0
      tests/TestCase/ORM/Association/HasManyTest.php

+ 1 - 1
src/ORM/Association/HasMany.php

@@ -484,7 +484,7 @@ class HasMany extends Association
                 return !in_array(null, $v, true);
             }
         )
-        ->toArray();
+        ->toList();
 
         $conditions = $foreignKeyReference;
 

+ 37 - 0
tests/TestCase/ORM/Association/HasManyTest.php

@@ -24,6 +24,7 @@ use Cake\ORM\Association;
 use Cake\ORM\Association\HasMany;
 use Cake\ORM\Entity;
 use Cake\TestSuite\TestCase;
+use Cake\Utility\Hash;
 
 /**
  * Tests HasMany class
@@ -1123,6 +1124,42 @@ class HasManyTest extends TestCase
 
     /**
      * Test that the associated entities are unlinked and deleted when they are dependent
+     * when associated entities array is indexed by string keys
+     *
+     * @return void
+     */
+    public function testSaveReplaceSaveStrategyDependentWithStringKeys()
+    {
+        $authors = $this->getTableLocator()->get('Authors');
+        $authors->hasMany('Articles', ['saveStrategy' => HasMany::SAVE_REPLACE, 'dependent' => true]);
+
+        $entity = $authors->newEntity([
+            'name' => 'mylux',
+            'articles' => [
+                ['title' => 'One Random Post', 'body' => 'The cake is not a lie'],
+                ['title' => 'Another Random Post', 'body' => 'The cake is nice'],
+                ['title' => 'One more random post', 'body' => 'The cake is forever']
+            ]
+        ], ['associated' => ['Articles']]);
+
+        $entity = $authors->save($entity, ['associated' => ['Articles']]);
+        $sizeArticles = count($entity->articles);
+        $this->assertEquals($sizeArticles, $authors->Articles->find('all')->where(['author_id' => $entity['id']])->count());
+
+        $articleId = $entity->articles[0]->id;
+        $entity->articles = [
+            'one' => $entity->articles[1],
+            'two' => $entity->articles[2],
+        ];
+
+        $authors->save($entity, ['associated' => ['Articles']]);
+
+        $this->assertEquals($sizeArticles - 1, $authors->Articles->find('all')->where(['author_id' => $entity['id']])->count());
+        $this->assertFalse($authors->Articles->exists(['id' => $articleId]));
+    }
+
+    /**
+     * Test that the associated entities are unlinked and deleted when they are dependent
      *
      * In the future this should change and apply the finder.
      *