Browse Source

Merge pull request #4429 from jeremyharris/issue-2461

Clearing HABTM (unique) when HABTM array is empty. Fixes #2461
Mark Story 11 years ago
parent
commit
a5291ae7eb

+ 4 - 0
lib/Cake/Model/Model.php

@@ -1201,6 +1201,10 @@ class Model extends Object implements CakeEventListener {
 				continue;
 			}
 
+			if (!isset($this->data[$modelName])) {
+				$this->data[$modelName] = array();
+			}
+
 			foreach ($fieldSet as $fieldName => $fieldValue) {
 				unset($this->validationErrors[$fieldName]);
 

+ 41 - 0
lib/Cake/Test/Case/Model/ModelWriteTest.php

@@ -1725,6 +1725,47 @@ class ModelWriteTest extends BaseModelTest {
 	}
 
 /**
+ * test that saving HABTM with an empty array will clear existing HABTM if
+ * unique is true
+ *
+ * @return void
+ */
+	public function testSaveHabtmEmptyData() {
+		$this->loadFixtures('Node', 'Dependency');
+		$Node = new Node();
+
+		$data = array(
+			'Node' => array('name' => 'New First')
+		);
+		$Node->id = 1;
+		$Node->save($data);
+
+		$node = $Node->find('first', array(
+			'conditions' => array('Node.id' => 1),
+			'contain' => array('ParentNode')
+		));
+
+		$result = Hash::extract($node, 'ParentNode.{n}.id');
+		$expected = array(2);
+		$this->assertEquals($expected, $result);
+
+		$data = array(
+			'ParentNode' => array()
+		);
+		$Node->id = 1;
+		$Node->save($data);
+
+		$node = $Node->find('first', array(
+			'conditions' => array('Node.id' => 1),
+			'contain' => array('ParentNode')
+		));
+
+		$result = Hash::extract($node, 'ParentNode.{n}.id');
+		$expected = array();
+		$this->assertEquals($expected, $result);
+	}
+
+/**
  * testSaveHabtmNoPrimaryData method
  *
  * @return void

+ 2 - 1
lib/Cake/Test/Fixture/DependencyFixture.php

@@ -30,6 +30,7 @@ class DependencyFixture extends CakeTestFixture {
  * @var array
  */
 	public $fields = array(
+		'id' => 'integer',
 		'child_id' => 'integer',
 		'parent_id' => 'integer'
 	);
@@ -40,6 +41,6 @@ class DependencyFixture extends CakeTestFixture {
  * @var array
  */
 	public $records = array(
-		array('child_id' => 1, 'parent_id' => 2),
+		array('id' => 1, 'child_id' => 1, 'parent_id' => 2),
 	);
 }