Virtual Attribute in Model

Hi,

Here is my situation.

I have a model called product.

I need every product can has its own attributes which will be generated by users.

So I have another model called attribute_type to keep type of attributes such as name, description, prize.

and another model called attribute_value to keep the value of the attribute types of each products.

So how can I create a virtual attribute for my product model so then I can called


$product->name

Let make it simple. I just want to call a field of the related model but like it is a field of itself.

Thanks,

have you tried to achieve your project with Relational AR

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);

}