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!
I solved this by adding a new ‘Conversation’ entity like so:
Then performing the following find: