Define relations at Runtime


I am implementing a Activity / update stream for a social networking site. I need to define relations at runtime based on the ‘activityType’ field value. For instance if its value is “photoalbum” it should relate to a photoalbum model or if its value is “Event” then it should relate to the event model.

I tried to do it like this:

	public function relations()


                $relations = array();




                    $relations = array(

                        'user' => array(self::BELONGS_TO, 'User', 'userId'),

                        'parent' => array(self::BELONGS_TO, $this->parentType, 'parentId'),



//                print_r($relations);

//                die();

		return $relations;


But, I get an error that the property Activity.parentType is not defined. Any idea how to fix this. I know we can define relation separately for every model. But this looks more cleaner and reduces redundancy.


Polymorphic associations? Probably not the best solution. Hope you’ll find this thread useful.

Thanks for the link. I am not defining foreign keys in my database, so its not an issue with MySQL. Rather it is giving error because its checking the relations before the values of the model are initialized (activityType not defined).

Is not possible to to define relations relying on the properies of the object.

Do you have many parent types? You can create a separate class (extending base class) for each type.

hi Chetan,

Did you find the solution for you proble, I’m also have the same problem, can you help me out from this problem.