Skip to content

Commit

Permalink
Adding tests for deletion of multiple habtm associations. Reverting c…
Browse files Browse the repository at this point in the history
…hanges made in [15518b8] that caused incorrect removal of links when deleting records.  Fixes #247
  • Loading branch information
markstory committed Jan 29, 2010
1 parent 3836592 commit 887ddb9
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 8 deletions.
13 changes: 5 additions & 8 deletions cake/libs/model/model.php
Original file line number Diff line number Diff line change
Expand Up @@ -1868,18 +1868,15 @@ function _deleteDependent($id, $cascade) {
*/
function _deleteLinks($id) {
foreach ($this->hasAndBelongsToMany as $assoc => $data) {
$with = $data['with'];
$records = $this->{$data['with']}->find('all', array(
'conditions' => array_merge(array(
$this->{$with}->escapeField($data['foreignKey']) => $id
)),
'fields' => $this->{$with}->primaryKey,
$joinModel = $data['with'];
$records = $this->{$joinModel}->find('all', array(
'conditions' => array_merge(array($this->{$joinModel}->escapeField($data['foreignKey']) => $id)),
'fields' => $this->{$joinModel}->primaryKey,
'recursive' => -1
));
if (!empty($records)) {
foreach ($records as $record) {
$id = $record[$this->{$with}->alias][$this->{$with}->primaryKey];
$this->{$with}->delete($id);
$this->{$joinModel}->delete($record[$this->{$joinModel}->alias][$this->{$joinModel}->primaryKey]);
}
}
}
Expand Down
35 changes: 35 additions & 0 deletions cake/tests/cases/libs/model/model_delete.test.php
Original file line number Diff line number Diff line change
Expand Up @@ -500,6 +500,41 @@ function testDeleteLinks() {
$this->assertTrue($result, 'deleteAll returned false when all no records matched conditions. %s');
}

/**
* test deleteLinks with Multiple habtm associations
*
* @return void
*/
function testDeleteLinksWithMultipleHabtmAssociations() {
$this->loadFixtures('JoinA', 'JoinB', 'JoinC', 'JoinAB', 'JoinAC');
$JoinA =& new JoinA();

//create two new join records to expose the issue.
$JoinA->JoinAsJoinC->create(array(
'join_a_id' => 1,
'join_c_id' => 2,
));
$JoinA->JoinAsJoinC->save();
$JoinA->JoinAsJoinB->create(array(
'join_a_id' => 1,
'join_b_id' => 2,
));
$JoinA->JoinAsJoinB->save();

$result = $JoinA->delete(1);
$this->assertTrue($result, 'Delete failed %s');

$joinedBs = $JoinA->JoinAsJoinB->find('count', array(
'conditions' => array('JoinAsJoinB.join_a_id' => 1)
));
$this->assertEqual($joinedBs, 0, 'JoinA/JoinB link records left over. %s');

$joinedBs = $JoinA->JoinAsJoinC->find('count', array(
'conditions' => array('JoinAsJoinC.join_a_id' => 1)
));
$this->assertEqual($joinedBs, 0, 'JoinA/JoinC link records left over. %s');
}

/**
* testHabtmDeleteLinksWhenNoPrimaryKeyInJoinTable method
*
Expand Down

0 comments on commit 887ddb9

Please sign in to comment.