Dynamic Relations To Model

Hello,

first of all, I would like to mention that I am very new to Yii.

From what I understand, in modelling the database with foreign keys I get some relations:


public function relations()

    {

        return array(

            'posts'=>array(self::HAS_MANY, 'Post', 'author_id'),

            'profile'=>array(self::HAS_ONE, 'Profile', 'owner_id'),

        );

    }

I would like to model these relations on the fly. Is that possible? Let’s say I have a table ServiceProvider and this table can be related either to a Person table or a Company table. I would not want to make foreign keys for every type of Service Provider that I can have so I create a “type” column that tells me what type that service provider is. Can I change my relation depending on that type attribute? Something like:


public function relations()

    {

        if ($this->type==1) return array(

            'posts'=>array(self::HAS_MANY, 'Post', 'author_id'),

            'profile'=>array(self::HAS_ONE, 'Profile', 'owner_id'),

        );

         else //return different relations

    }

What I would want to achieve is a uniform process to work with service providers no matter the type. If the solution above does not work, could you suggest another one?

Thank you very much for your time!

You would want to to put the additional condition for the relation in the ‘on’ clause:




public function relations()

{

    return array(

        'posts'=>array(self::HAS_MANY, 'Post', 'author_id', 'on'=>'t.type = 1'),

        'profile'=>array(self::HAS_ONE, 'Profile', 'owner_id', 'on'=>'t.type = 1'),

        'tickets'=>array(self::HAS_MANY, 'Tickets', 'author_id', 'on'=>'t.type = 2'),

        'providerProfile'=>array(self::HAS_ONE, 'Provider', 'owner_id', 'on'=>'t.type = 2'),

    );

}



Thanks!