My question concerns how I can use one comments c开发者_开发技巧ontroller with multiple 'belongs to' controllers.
I want to add comments to news, posts, and matches (it's a tennis website). I've got the comments add action setup to use the 'ajax' helper and I'm also using counterCache
to keep track of the number of comments for each news, post and match.
What I don't know, is how to pass in the unique ID (news, posts, matches) into the comments controller add action so the form saves the comment and news_id, post_id or match_id, whichever is passed in the form.
What I'm thinking is if the form is setup to collect the unique ID in such a way that what gets passed is specific to that controller (news,post,match). The result would be that the add action adds the comment along with the news/post/match ID value.
Otherwise I'd have to setup a post_comments, news_comments and match_comments controller to handle each, and that wouldn't be the DRY approach I'm after.
I'm still building my knowledge and understanding of CakePHP. How can I achive what I have set out to do?
Your comment database table should look like this:
id | belongs_to | foreign_id | ....
-------------------------------------
| | |
belongs_to
is either enum
or varchar
Then in your model you can associate the comment model like this in the comment model:
var $belongsTo = array(
'News' => array(
'className' => 'News',
'foreignKey' => 'foreign_id',
'conditions' => array('Comment.belongs_to'=>'News'),
'fields' => '',
'order' => ''
),
'Post' => array(
'className' => 'Post',
'foreignKey' => 'foreign_id',
'conditions' => array('Comment.belongs_to'=>'Post'),
'fields' => '',
'order' => ''
)
);
And in the Post-Model:
var $hasMany = array(
'Comment' => array(
'className' => 'Comment',
'foreignKey' => 'foreign_id',
'dependent' => true,
'conditions' => array('Comment.belongs_to' => 'Post'),
'fields' => '',
'order' => 'Comment.created DESC',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
)
);
精彩评论