CakePHP: Associate the same models twice
Posted on : 05-08-2008 | By : Chuck | In : Uncategorized
1
The new GreeneCountyIndiana.com CMS allows users to post comments on News articles. Of course, when you let users post comments, you need a good method of moderation. It would be very difficult for the site admins to moderate every single comment, so we are adding a “Report this comment” button so regular users can report comments for administrators to review.
When a user clicks the Report comment button it sets a ‘reported’ field in the database to true, and sets a ‘reported_by’ field to the id of the user that reported it.
Comment already belongsTo Users once, as it stores the user that posted the comment. Comment needs another belongsTo User association for grabbing the username and other details of the person who reported the comment.
The solution is actually very simple.
var $belongsTo = array(
'User' => array('className' => 'User', 'foreignKey' => 'user_id'),
'Reporter' => array('className' => 'User', 'foreignKey' => 'reporter_id')
);
The first association:
'User' => array('className' => 'User', 'foreignKey' => 'user_id'),
associates each Comment with the User that posted it.
The second association:
'Reporter' => array('className' => 'User', 'foreignKey' => 'reporter_id')
associates each comment with the User that reported it.
Essentially, all it does is copy the User model under the name “Reporter.” Simple, and it works like a charm.




