Skip to content

Commit

Permalink
Clearing HABTM (unique) when HABTM array is empty, refs #2461
Browse files Browse the repository at this point in the history
  • Loading branch information
jeremyharris committed Aug 28, 2014
1 parent 4922729 commit 2dac6d2
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 1 deletion.
4 changes: 4 additions & 0 deletions lib/Cake/Model/Model.php
Expand Up @@ -1201,6 +1201,10 @@ public function set($one, $two = null) {
continue;
}

if (!isset($this->data[$modelName])) {
$this->data[$modelName] = array();
}

foreach ($fieldSet as $fieldName => $fieldValue) {
unset($this->validationErrors[$fieldName]);

Expand Down
41 changes: 41 additions & 0 deletions lib/Cake/Test/Case/Model/ModelWriteTest.php
Expand Up @@ -1724,6 +1724,47 @@ public function testSaveHabtm() {
$this->assertEquals($expected, Hash::extract($result, 'JoinC.{n}.JoinAsJoinC.other'));
}

/**
* 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
*
Expand Down
3 changes: 2 additions & 1 deletion lib/Cake/Test/Fixture/DependencyFixture.php
Expand Up @@ -30,6 +30,7 @@ class DependencyFixture extends CakeTestFixture {
* @var array
*/
public $fields = array(
'id' => 'integer',
'child_id' => 'integer',
'parent_id' => 'integer'
);
Expand All @@ -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),
);
}

0 comments on commit 2dac6d2

Please sign in to comment.