2015-09-17 42 views
0

我正在嘗試與相應的用戶獲取消息,以便按時間順序顯示包含其最後一條消息的配置文件的聊天列表。CakePHP查找()組和按日期排序的複雜條件

array(
    0 => array(
     'Recepient' => array(
      'id' => ... 
      'name' => ... 
      ... 
     ), 
     'Message' => array(
      'content' => ... 
      'created' => ... 
      ... 
     ) 
    ), 
    1 => ... 
) 

,並以檢索結果,我寫這個find()方法:

$msgs = $this->Message->find('all', array(
    'group' => array('Recepient.id'), 
    'order'=>'Message.created DESC', 
    'conditions'=> 
     array(
      'OR'=> array(
       array('recepient_id'=>$pid), 
       array('sender_id' => $pid) 
      ) 
    ) 
)); 

我有什麼:

  • 消息相對應的 「Recepient」,
  • 按時間順序

問題:

  • 該查詢不檢索來自$ recepient_id/$ sender_id組合的最新消息。

因此,不是具有最後一條消息的用戶列表,我有一個帶有消息的用戶列表。我的查詢有什麼問題?感謝幫助!

方法2個結果

我創建了一個基本上是數據庫「chat_id」字段recepient_id + SENDER_ID字母順序排序(因爲如果用戶1發送用戶2的消息user1的發送者,後來當user2的迴應,他成爲發件人,所以排序將確保兩個用戶將始終具有相同的chat_id)。

比我還清晰地向查詢:

$this->Message->recursive = 0; $msgs = $this->Message->find('all', array( 'fields' => array('DISTINCT Message.chat_id','Message.*','Recepient.*'), 'order'=>'Message.created DESC', 'conditions'=> array( 'OR'=> array( array('recepient_id'=>$pid), array('sender_id' => $pid) ) ) ));

,它不工作!我現在正在爲同一個對話收到多封郵件。

如果我從查詢中刪除消息字段和收件人字段,我會得到正確數量的「聊天」。 'fields' => array('DISTINCT Message.chat_id'), 但這不是解決方案。

的CakePHP版本2.7.0 MySQL數據庫

方法3個結果

$msgs = $this->Message->find('all', array( 'order'=>'Message.created DESC', 'fields' => 'recepient_id, content, max(Message.created) as max_created', 'group'=>'recepient_id', // 'contain' => array('Recepient'), 'conditions'=>array('chat_id' => $chats) ));

我放棄了在單找到方法來解決這個問題,所以現在1.I我得到的聊天列表2.我想從每次聊天中找到最後一條消息。 根據http://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql/我發現的查詢應該可以工作。什麼情況是

(int) 0 => array(
     'Message' => array(
      'recepient_id' => '55e6d764-1444-4aad-a909-9042f07f76da', 
      'content' => '1st msg', 
      'created' => '2015-09-20 18:24:17', 
      'created_nice' => '2 hours ago' 
     ), 
     (int) 0 => array(
      'max_created' => '2015-09-20 18:24:28' 
     ) 
    ), 

領域max(消息.創建)確實展示了最新的消息,從談話但是0 =>信息排列是不同的消息!正如你所見,$results[0]['Message']['created']時間和$results[0][0]['max_created']是不同的!

+0

'消息'有很多'收件人'嗎?你有沒有檢查過Cake發現的這個查詢的SQL查詢?我懷疑這個查詢不是你所期望的! – drmonkeyninja

+1

您使用的是CakePHP的哪個版本? –

+0

聽起來像'distinct'是一個你應該看看的術語......在[書]中有'distinct'的外觀(http://book.cakephp.org/2.0/en/models/retrieving-your -data.html)... –

回答

0

終於!工作解決方案:

$db = $this->Message->getDataSource(); 
$chats = $db->fetchAll(
    'select id from (select * from messages order by created desc) Message 
    where recepient_id = "'.$pid.'" or sender_id = "'.$pid.'" 
    group by `chat_id`' 
); 

上面的代碼將檢索所有消息,遵循要求。您可以

一)單個查詢添加MySQL JOIN包括關聯的模型(我們保持代碼的單一查詢整齊)

B)兩個查詢,但更聰明更簡單的方法,只選擇「IDS」的消息,並創建另一個查詢,將蛋糕的建立在可容納的行爲。這可能會更好,因爲行爲將被應用。

您將有樹陣,結果挖出了一個查詢的實際使用IDS如下:

$chats = Set::extract("/Message/id",$chats);

C)翻譯解決方案,CakePHP的查詢生成器... :)彌補一個挑戰?