This is my first question on stackoverflow so be nice if i'm doing some mistakes. Here's my problem :
- I'm working on a messaging system and in my inbox function i want to list every conversations owned by the current logged in user. This is not a problem but then i want, for each conversation, list every users that owns it too (= recipients).
Here is how i'm dealing with it :
function inbox()
{
$conversationIDs = $this->ConversationUser->find('list', array(
'fields' => array('ConversationUser.conversation_id'),
'conditions' => array('user_id' => $this->Session->read('Auth.User.id')),
'recursive' => -1
));
$i = 0;
foreach($conversationIDs as $conversation)
{
$array = $this->ConversationUser->find('first', array(
'fields' => array('ConversationUser.conversation_id', 'ConversationUser.user_id', 'Conversation.subject', 'User.username'),
'conditions' => array('ConversationUser.conversation_id' => $conversation,
'NOT' => array('ConversationUser.user_id' => $this->Session->read('Auth.User.id'))
),
'recursive' => 1
));
$result[$i] = $array;
$i++;
$this->set(compact('result'));
}
}
I'm gathering every conversation's id that the current user owns then "foreach" theses ids to find every users in these conversations.
Actually it is working very fine but i find the solution a bit dirty. Is there a better way to foreach in controller then pass this in view better than this ?
Or maybe my approach is very bad and i should do in a completely other way ?
Edit :
In my Conversation Model :
public function getConversations($userID)
{
$conversationsIDs = $this->ConversationUser->find('list', array(
'fields' => array('ConversationUser.conversation_id'),
'conditions' => array('ConversationUser.user_id' => $userID),
'recursive' => -1,
));
$conversations = $this->find('all', array(
'conditions' => array(
'Conversation.id IN('.implode(",", $conversationsIDs).')'
),
'contain' => array(
'LastMessage' => array(
'User' => array(
'fields' => array('User.username')
)
),
'ConversationUser' => array(
'User' => array(
'fields' => array('User.username')
)
)
)
));
return $conversations;
}
In my Conversation controller :
function inbox()
{
$conversations = $this->Conversation->getConversations($this->Session->read('Auth.User.id'));
$this->set(compact("conversations"));
}
What do you think about it ? Actually it's working really fine for me. :)