From 7790bcacffa8ad33bb94e4fad0f8b9f092e3ffb9 Mon Sep 17 00:00:00 2001 From: mark_story Date: Thu, 17 Jan 2013 20:35:37 -0500 Subject: [PATCH] Allow afterFind() to fully remove an associated record. By returnning array() or unsetting the 0'th result an afterFind callback should be able to fully remove data from the results. Fixes #3541 --- lib/Cake/Model/Datasource/DboSource.php | 4 +++- lib/Cake/Test/Case/Model/ModelReadTest.php | 24 ++++++++++++++++++++++ lib/Cake/Test/Case/Model/models.php | 10 +++++++++ 3 files changed, 37 insertions(+), 1 deletion(-) diff --git a/lib/Cake/Model/Datasource/DboSource.php b/lib/Cake/Model/Datasource/DboSource.php index c84171810..fc09feb10 100644 --- a/lib/Cake/Model/Datasource/DboSource.php +++ b/lib/Cake/Model/Datasource/DboSource.php @@ -1153,10 +1153,12 @@ class DboSource extends DataSource { } $linkedModel = $model->{$className}; $filtering[] = $className; - foreach ($results as &$result) { + foreach ($results as $key => &$result) { $data = $linkedModel->afterFind(array(array($className => $result[$className])), false); if (isset($data[0][$className])) { $result[$className] = $data[0][$className]; + } else { + unset($results[$key]); } } } diff --git a/lib/Cake/Test/Case/Model/ModelReadTest.php b/lib/Cake/Test/Case/Model/ModelReadTest.php index 65e7f90eb..8ad2bd4e0 100644 --- a/lib/Cake/Test/Case/Model/ModelReadTest.php +++ b/lib/Cake/Test/Case/Model/ModelReadTest.php @@ -3006,6 +3006,30 @@ class ModelReadTest extends BaseModelTest { $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 * diff --git a/lib/Cake/Test/Case/Model/models.php b/lib/Cake/Test/Case/Model/models.php index b86a4b583..7dd8fc3db 100644 --- a/lib/Cake/Test/Case/Model/models.php +++ b/lib/Cake/Test/Case/Model/models.php @@ -551,6 +551,13 @@ class ModifiedComment extends CakeTestModel { */ public $useTable = 'comments'; +/** + * Property used to toggle filtering of results + * + * @var boolean + */ + public $remove = false; + /** * belongsTo property * @@ -567,6 +574,9 @@ class ModifiedComment extends CakeTestModel { if (isset($results[0])) { $results[0]['Comment']['callback'] = 'Fire'; } + if ($this->remove) { + return array(); + } return $results; }