Browse Source

Associations can now be fetched as properties in a table

Jose Lorenzo Rodriguez 12 years ago
parent
commit
bfa3b9c58c
2 changed files with 58 additions and 0 deletions
  1. 31 0
      src/ORM/Table.php
  2. 27 0
      tests/TestCase/ORM/TableTest.php

+ 31 - 0
src/ORM/Table.php

@@ -1501,6 +1501,37 @@ class Table implements RepositoryInterface, EventListener {
 	}
 
 /**
+ * Returns the association named after the passed value if exists, otherwise
+ * throws an exception.
+ *
+ * @param string $property the association name
+ * @return \Cake\ORM\Association
+ * @throws \RuntimeException if no association with such name exists
+ */
+	public function __get($property) {
+		$association = $this->_associations->get($property);
+		if (!$association) {
+			throw new \RuntimeException(sprintf(
+				'Table "%s" is not associated with "%s"',
+				get_class($this),
+				$property
+			));
+		}
+		return $association;
+	}
+
+/**
+ * Returns whether an association named after the passed value
+ * exists for this table.
+ *
+ * @param string $property the association name
+ * @return boolean
+ */
+	public function __isset($property) {
+		return $this->_associations->has($property);
+	}
+
+/**
  * Get the object used to marshal/convert array data into objects.
  *
  * Override this method if you want a table object to use custom

+ 27 - 0
tests/TestCase/ORM/TableTest.php

@@ -3274,4 +3274,31 @@ class TableTest extends \Cake\TestSuite\TestCase {
 		$this->assertEquals($expected, $result);
 	}
 
+/**
+ * Tests that it is possible to get associations as a property
+ *
+ * @return void
+ */
+	public function testAssociationAsProperty() {
+		$articles = TableRegistry::get('articles');
+		$articles->hasMany('comments');
+		$articles->belongsTo('authors');
+		$this->assertTrue(isset($articles->authors));
+		$this->assertTrue(isset($articles->comments));
+		$this->assertFalse(isset($articles->posts));
+		$this->assertSame($articles->association('authors'), $articles->authors);
+		$this->assertSame($articles->association('comments'), $articles->comments);
+	}
+
+/**
+ * Tests that getting a bad property throws exception
+ *
+ * @expectedException \RuntimeException
+ * @expectedExceptionMessage Table "TestApp\Model\Table\ArticlesTable" is not associated with "posts"
+ * @return void
+ */
+	public function testGetBadAssociation() {
+		$articles = TableRegistry::get('articles');
+		$articles->posts;
+	}
 }