Cakephp按相关模型订购

时间:2013-05-28 08:58:31

标签: cakephp model-associations

我有以下模型关联:

//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混合在一起并按日期排序。我该怎么做?

1 个答案:

答案 0 :(得分:0)

您可以从Message模型而不是User模型中进行查询吗?

例如:

$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'
    )
);