Permalink
Browse files

Implementing Model::relationships()

  • Loading branch information...
1 parent 16c70cc commit 0822f7b8463f3932e941c9fe89ef1190a1807b09 @jails jails committed Jul 13, 2012
Showing with 38 additions and 1 deletion.
  1. +24 −0 data/Model.php
  2. +14 −1 tests/cases/data/ModelTest.php
View
24 data/Model.php
@@ -165,6 +165,13 @@ class Model extends \lithium\core\StaticObject {
protected $_relations = array();
/**
+ * An array containing the match between fieldname and their corresponding relation name.
+ *
+ * @var array
+ */
+ protected $_relationships = array();
+
+ /**
* List of relation types.
*
* Valid relation types are:
@@ -642,6 +649,22 @@ public static function relations($name = null) {
}
/**
+ * Returns the relation name associated to a field name, or a list of field name associated
+ * to their to corresponding relation name if `$fieldname` is null.
+ *
+ * @param string $fieldname A fieldname.
+ * @return mixed A relation name or an array of associations.
+ */
+ public static function relationships($fieldname = null) {
+ $self = static::_object();
+
+ if (!$fieldname) {
+ return $self->_relationships;
+ }
+ return isset($self->_relationships[$fieldname]) ? $self->_relationships[$fieldname] : null;
+ }
+
+ /**
* Creates a relationship binding between this model and another.
*
* @see lithium\data\model\Relationship
@@ -661,6 +684,7 @@ public static function bind($type, $name, array $config = array()) {
throw new ConfigException("Invalid relationship type `{$type}` specified.");
}
$rel = static::connection()->relationship(get_called_class(), $type, $name, $config);
+ $self->_relationships[$rel->fieldName()] = $name;
return $self->_relations[$name] = $rel;
}
View
15 tests/cases/data/ModelTest.php
@@ -790,6 +790,19 @@ public function testLiveConfiguration() {
$result = MockBadConnection::meta('connection');
$this->assertFalse($result);
}
+
+ public function testRelationships() {
+ MockPost::bind('hasMany', 'MockTag');
+ $relationships = MockPost::relationships();
+ $this->assertEqual(array(
+ 'mock_comments' => 'MockComment',
+ 'mock_tags' => 'MockTag'
+ ), $relationships);
+
+ $this->assertEqual('MockComment', MockPost::relationships('mock_comments'));
+ $this->assertEqual('MockTag', MockPost::relationships('mock_tags'));
+ $this->assertNull(MockPost::relationships('undefined'));
+ }
}
-?>
+?>

0 comments on commit 0822f7b

Please sign in to comment.