Skip to content

Commit

Permalink
Associations can now be fetched as properties in a table
Browse files Browse the repository at this point in the history
  • Loading branch information
lorenzo committed Mar 22, 2014
1 parent 1a31f2b commit bfa3b9c
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 0 deletions.
31 changes: 31 additions & 0 deletions src/ORM/Table.php
Expand Up @@ -1500,6 +1500,37 @@ public function __call($method, $args) {
);
}

/**
* 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.
*
Expand Down
27 changes: 27 additions & 0 deletions tests/TestCase/ORM/TableTest.php
Expand Up @@ -3274,4 +3274,31 @@ public function testDebugInfo() {
$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;
}
}

0 comments on commit bfa3b9c

Please sign in to comment.