I wanted to do something similar, i.e. access the attributes of a related model as though they were attributes of the parent model; e.g. $parent->related->attribute and $parent->attribute would return the same thing.
My solution was to override the __get(), __set(), and __isset() magic functions in the parent model as below.
These check to see if the parent model has the attribute $name or not; if not the related model is fetched and tested to see if it has the attribute $name. If it does this is returned/set/tested; if not parent::__magicFuntion() is called.
// Change 'relationship' to the required relationship name
public function __get($name) {
if (!$this->hasAttribute($name)) {
$r = parent::__get('relationship');
if ($r->hasAttribute($name))
return $r->$name;
}
return parent::__get($name);
}
public function __set($name,$value) {
if (!$this->hasAttribute($name)) {
$r = parent::__get('relationship');
if ($r->hasAttribute($name))
return ($r->$name = $value);
}
return parent::__set($name,$value);
}
public function __isset($name) {
if (!$this->hasAttribute($name)) {
$r = parent::__get('relationship');
if ($r->hasAttribute($name))
return isset($r->$name);
}
return parent::__isset($name);
}