2013-05-28 156 views
0

我有以下型號協會:CakePHP的順序由關聯模型

//User Model 
public $hasMany = array(
    'MessageSent' => array(
     'className' => 'Message', 
     'foreignKey' => 'sender_id' 
    ), 
    'MessageReceived' => array(
     'className' => 'Message', 
     'foreignKey' => 'receiver_id' 
    )); 

//Message Model 
public $belongsTo = array(
    'Sender' => array(
     'className' => 'User', 
     'foreignKey' => 'sender_id' 
    ), 
    'Receiver' => array(
     'className' => 'User', 
     'foreignKey' => 'receiver_id' 
    ) 
); 

現在我想取得與由「創建」命令消息的用戶,這樣我可以創造ALA Facebook的消息流。

$this->User->contain(array(
    'MessageSent' => array('conditions' => array('MessageSent.receiver_id' => 
     $this->Auth->user('id'))), 
    'MessageReceived' => array('conditions' => array('MessageReceived.sender_id' => 
     $this->Auth->user('id'))) 
    )); 
$partner = $this->User->find('all', array('conditions' => array('slug' => 
    $this->request->params['slug']))); 

所以我需要一些像「ORDER BY Message.created」,讓我得到MessageSent和的messageReceived混合在一起,並按照時間先後。我怎麼做?

回答

0

你可以只從消息模型,而不是用戶模型查詢嗎?

例如:

$userId = $this->Auth->user('id'); 
$this->Message->find('all', 
    array(
     'conditions' => array(
      'OR' => array(
       'Message.sender_id' => $userId, 
       'Message.receiver_id' => $userId 
      ) 
     ), 
     'contain' => array('Sender', 'Receiver'), 
     'order' => 'Message.created DESC' 
    ) 
);