Reputation: 689
I would like to have a simple and reusable way of sharing a relations with a specific table with different models. What I would like to do is the possibility to specify a table, with a foreign key column such as "parent_id" and then associate this table/model to several models in my app. Is there a way to do this in cake, and which is the best way? I guess I would need an additional column in this table, to specify which is the table every row is linked to, e.g.:
Table1
id 0 1 2 name name0 name1 name2 ...
Table2
id 0 1 2 name name0 name1 name2 ...
Common_table:
id 0 1 ... parent_id 0 0 parent_table Table1 Table2
I hope the explanation above made sense, thanks in advance!
Upvotes: 0
Views: 56
Reputation: 9398
yes
when you create a relationship you can also set the conditions
An example could be an application in which you have many models that can be commented, so they all are in a hasMany relationship with Comment
Model.
You can create a column in comments table storing the name of the model being commented and a parent_id
column storing the id.
So the comments table would tipically be something like
id | parent_id | model_name | comment_text | user_id
---+-----------+------------+----------------------+-------
1 | 15 | Post | I like this Post | 3
1 | 15 | Post | I like this Post too | 5
2 | 19 | Receipt | This receipt is good | 3
in your Post
Model you can do
public hasMany =array(
'Comment' => array(
'foreignKey' => 'parent_id',
'conditions' => array('Comment.model_name' => 'Post')
)
in your Receipt
Model you can do
public hasMany =array(
'Comment' => array(
'foreignKey' => 'parent_id',
'conditions' => array('Comment.model_name' => 'Receipt')
)
and so on
Upvotes: 1