Browse Source

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
mark_story 13 years ago
parent
commit
7790bcacff

+ 3 - 1
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]);
 				}
 			}
 		}

+ 24 - 0
lib/Cake/Test/Case/Model/ModelReadTest.php

@@ -3007,6 +3007,30 @@ class ModelReadTest extends BaseModelTest {
 	}
 
 /**
+ * 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
  *
  * @return void

+ 10 - 0
lib/Cake/Test/Case/Model/models.php

@@ -552,6 +552,13 @@ class ModifiedComment extends CakeTestModel {
 	public $useTable = 'comments';
 
 /**
+ * Property used to toggle filtering of results
+ *
+ * @var boolean
+ */
+	public $remove = false;
+
+/**
  * belongsTo property
  *
  * @var array
@@ -567,6 +574,9 @@ class ModifiedComment extends CakeTestModel {
 		if (isset($results[0])) {
 			$results[0]['Comment']['callback'] = 'Fire';
 		}
+		if ($this->remove) {
+			return array();
+		}
 		return $results;
 	}