Harsha M V
Harsha M V

Reputation: 54949

CakePHP: Doing Complex Find

In my application i have a threaded commenting system which i call status messages. i have a few models as follows

users(id, name......)

status_messages(id, message,......, user_id)

status_replies(id, message,......, status_message_id, user_id)

is this the right way of writing a commenting system ?

A user can set status messages and his friends and himself can reply to it. if another user replies i would want to pull out his details also.

alt text

Upvotes: 1

Views: 263

Answers (3)

Stephen
Stephen

Reputation: 18964

Use the Containable Behavior in the model public $actsAs = array('Containable');

Then, from the User Controller:

$userWithMessagesAndReplies = $this->User->find('first' => array(
        'conditions' => array(/* conditions for finding the user (User.id) */),
        'contain' => array(
            'StatusMessage' => array('StatusReply')
        )
    )
);

This is just an example. Depending on where you do the find, you would change the code above slightly. I would recommend returning the results of the find from a model method instead of a controller so that it is reusable. (I used a controller example for ease of understanding.)

Upvotes: 1

Abba Bryant
Abba Bryant

Reputation: 4012

I don't think you need 2 tables.

Use a single messages table and create 2 models that both use that table.

I.E table = messages, Models = ProfileMessage, ProfileReply

In that table make sure there is a profile_id, a user_id
and a parent_id. Default all of these to null.

Relate the ProfileMessage as
    belongsTo User, 
    belongsTo Profile,
    hasMany ProfileReply

Relate the ProfileReply as
    belongsTo ProfileMessage using the foreignKey key in the association to make sure you reference the parent_id and profile_id,
    belongsTo User

Then you can just query the ProfileMessage and it should show all of the child ProfileReply objects as if they came from a separate related table. Basically a single level tree structure relates the entries to their parent entries in the same table.

Upvotes: 1

Adam
Adam

Reputation: 5070

If you want a threaded comment system you should consider using the Tree or MultiTree behavior, with find('threaded').

Upvotes: 1

Related Questions