Featured Posts

Supreme Court Rules Against FCC, Net Neutrality Not a good day for net neutrality... A federal court threw the future of Internet regulations into doubt Tuesday with a far-reaching decision that went against the Federal...

Read More »

The Fog Machine has Arrived My Chauvet Hurricane 1300 arrived today. First thing's first--immediately unpack it, add some fog juice, and play! [caption id="attachment_81" align="aligncenter" width="225"...

Read More »

Realestate Manager 2.0 Picture Preview Since Real Estate Manager 2.0 is now almost ready for release, I figured I would share the differences between the current version (1.1) and 2.0. To start things off, the...

Read More »

Automotive Manager Photo Update It's been less than 2 months since I started on Automotive Manager. In that time, I've taken the thing from next to nothing to an almost complete product. I'm not sure how...

Read More »

The New GreeneCountyIndiana.com Since about March I have been working (rather slowly) on a new content management system for GreeneCountyIndiana.com. Along with it comes a new layout and many new features. The...

Read More »

Chuck’s Blog Rss A scary bee!!!

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.

Comments (1)

How do you set up your users model?

Write a comment