Search code examples
cakephp-2.0belongs-to

how to set belongTo relation in cakephp model depending on a field?


I have a table notifications as following :

id
parent_type
parent_id

parent_type can be story or chapter or content

I want to tell Notification model :

-if the parent_type is story then parent_id will be a foreign key in Story -if the parent_type is chapter then parent_id will be a foreign key in Chapter -if the parent_type is content then parent_id will be a foreign key in Content

Is that possible ?

Thank you


Solution

  • When you look into book here:

    http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#belongsto

    it says, you can set conditions in belongsTo definition. So you can define three different belongsTo associations with different conditions, for example:

    public $belongsTo = array(
        'Story' => array(
            'className' => 'Story',
            'foreignKey' => 'parent_id',
            'conditions' => array('Notification.parent_type' => 'story')
        ),
        ...
    );