Q:

CakePHP Messaging System

I'm trying to implement a simple messaging system in CakePHP 1.3. What I need to do is perform a query to return an array of users that my logged in user is having a conversation with (so has either received a message from, sent a message to, or both).
My User model is set up like so:
class User extends AppModel {
    var $name = 'User';
    var $actsAs = array('Containable');

    var $hasMany = array(

        'SentMessages' =>
        array (
            'className' => 'Message',
            'foreignKey' => 'sender_id'
        ),

        'ReceivedMessages' =>
        array (
            'className' => 'Message',
            'foreignKey' => 'receiver_id'
        )
    );  
}

I can use Containable to retrieve just the User and their related messages, and add conditions to those Contain statements to limit those messages to the ones between each user and my logged in user.
$users = $this->User->find('all', array(
    'contain' => array(
        'ReceivedMessages' => array(
            'conditions' => array(
                'receiver_id' => $my_user_id
            )
        ),
        'SentMessages' => array(
            'conditions' => array(
                'sender_id' => $my_user_id
            )
        )
    )
));

However, this still returns EVERY user in my DB. Is there a way to write this query so that only the Users with any SentMessages or ReceivedMessages are returned?
Thanks!

A:

I solved this by adding a new 'Conversation' entity like so:
var $hasMany = array(
    'Message' => array(
        'className' => 'Message',
        'foreignKey' => 'conversation_id'
    )
);

var $belongsTo = array(
    'FirstUser' => array(
        'className' => 'User',
        'foreignKey' => 'first_user_id'
    ),
    'SecondUser' => array(
        'className' => 'User',
        'foreignKey' => 'second_user_id'
    )
);

Then performing the following find:
$conversations = $this->Conversation->find('all',array(
    'conditions' => array(
        'OR' => array(
            'Conversation.first_user_id' => $this->my_user_id,
            'Conversation.second_user_id' => $this->my_user_id
        ),
        'Conversation.modified >' => date("Y-m-d H:i:s", $since_timestamp)
    )
);

