How do I pass multiple model identifiers in comments to add an action in CakePHP?

My question is about how I can use one comment controller with multiple "belongs" controllers.

I want to add comments to news, messages and matches (this is a site for tennis). I have comments adding action settings for using the "ajax" helper, and I also use counterCache to track the number of comments for each news, post, and correspondence.

I don’t know how to pass a unique identifier (news, messages, matches) to the comment controller in order to add an action so that the form saves the comment and news_id, post_id or match_id, depending on what is submitted in the form.

I think that if the form is configured to collect a unique identifier in such a way that what is transmitted is specific to this controller (news, mail, coincidence). The result is that adding a comment will add a comment along with the value of the news / message / match identifier.

Otherwise, I would have to configure the post_comments, news_comments and match_comments controllers to handle each of them, and that would not be DRY I am after.

I am still building my knowledge and understanding of CakePHP . How can I achieve what I have done?

+4
source share
1 answer

Your comment database table should look like this:

 id | belongs_to | foreign_id | .... ------------------------------------- | | | 

belongs_to either enum or varchar

Then in your model you can link the comment model, as it is 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' => '' ) ); 
+2
source

Source: https://habr.com/ru/post/1301475/


All Articles