Skip to content

Commit

Permalink
Allow afterFind() to fully remove an associated record.
Browse files Browse the repository at this point in the history
By returnning array() or unsetting the 0'th result an afterFind
callback should be able to fully remove data from the results.

Fixes #3541
  • Loading branch information
markstory committed Jan 18, 2013
1 parent 773666d commit 7790bca
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 1 deletion.
4 changes: 3 additions & 1 deletion lib/Cake/Model/Datasource/DboSource.php
Expand Up @@ -1153,10 +1153,12 @@ protected function _filterResults(&$results, Model $model, $filtered = array())
} }
$linkedModel = $model->{$className}; $linkedModel = $model->{$className};
$filtering[] = $className; $filtering[] = $className;
foreach ($results as &$result) { foreach ($results as $key => &$result) {
$data = $linkedModel->afterFind(array(array($className => $result[$className])), false); $data = $linkedModel->afterFind(array(array($className => $result[$className])), false);
if (isset($data[0][$className])) { if (isset($data[0][$className])) {
$result[$className] = $data[0][$className]; $result[$className] = $data[0][$className];
} else {
unset($results[$key]);
} }
} }
} }
Expand Down
24 changes: 24 additions & 0 deletions lib/Cake/Test/Case/Model/ModelReadTest.php
Expand Up @@ -3006,6 +3006,30 @@ public function testSelfAssociationAfterFind() {
$this->assertEquals($afterFindData, $noAfterFindData); $this->assertEquals($afterFindData, $noAfterFindData);
} }


/**
* Test that afterFind can completely unset data.
*
* @return void
*/
public function testAfterFindUnset() {
$this->loadFixtures('Article', 'Comment', 'User');
$model = new CustomArticle();
$model->bindModel(array(
'hasMany' => array(
'ModifiedComment' => array(
'className' => 'ModifiedComment',
'foreignKey' => 'article_id',
)
)
));
$model->ModifiedComment->remove = true;
$result = $model->find('all');
$this->assertTrue(
empty($result[0]['ModifiedComment']),
'Zeroith row should be removed by afterFind'
);
}

/** /**
* testFindThreadedNoParent method * testFindThreadedNoParent method
* *
Expand Down
10 changes: 10 additions & 0 deletions lib/Cake/Test/Case/Model/models.php
Expand Up @@ -551,6 +551,13 @@ class ModifiedComment extends CakeTestModel {
*/ */
public $useTable = 'comments'; public $useTable = 'comments';


/**
* Property used to toggle filtering of results
*
* @var boolean
*/
public $remove = false;

/** /**
* belongsTo property * belongsTo property
* *
Expand All @@ -567,6 +574,9 @@ public function afterFind($results, $primary = false) {
if (isset($results[0])) { if (isset($results[0])) {
$results[0]['Comment']['callback'] = 'Fire'; $results[0]['Comment']['callback'] = 'Fire';
} }
if ($this->remove) {
return array();
}
return $results; return $results;
} }


Expand Down

0 comments on commit 7790bca

Please sign in to comment.