如何检索Cake中哪个用户是消息?

时间:2013-03-26 07:53:03

标签: mysql cakephp

我在CakePHP中创建了一个消息系统,我有表消息

id
from_id
to_id
subject
message

to_id被设置为用户的FK,因此用户可以拥有多条消息,但如果我只获取id,我该如何回显发件人的姓名?

用户模型:

class User extends AppModel {

public $name = 'User';

public $hasOne = array (
    'UserProfile'=>array(
        'className'=>'UserProfile',
        'foreignKey'=>'id'
    )
);

public $hasMany = array(
    'Message'=>array(
        'className'=>'Message',
        'foreignKey'=>'to_id'
    )
);
}

消息模型:

class Message extends AppModel {

public $name = 'Message';

public $belongsTo = array (
    'User'=>array(
        'className'=>'User',
        'foreignKey'=>'to_id'
    ),
);
}

消息控制器:

public function messages(){

    $user = $this->User->find(  'first', array('conditions' => array(
        'User.id' => $this->Session->read('Auth.User.id'))));
    $this->set('user', $user);


    if($this->request->is('post')) {
        $this->requert->data['Message']['from_id'] = $this->Auth->user('id');
        debug($this->request->data);
    }
}

这需要在数组中存储有关用户的所有信息,包括数组Message,但在这种情况下,我得到了arrat消息:

id => 1
from_id => 10
to_id => 7
subject => 'subject'
message => 'body'

那么如何从此ID中提取发件人姓名?

请帮帮忙?

1 个答案:

答案 0 :(得分:1)

在这种情况下,您需要为classNames使用别名。

class Message extends AppModel {
    public $belongsTo = array(
        'Sender' => array(
            'className' => 'User',
            'foreignKey' => 'from_id'
        ),
        'Receiver' => array(
            'className' => 'User',
            'foreignKey' => 'to_id'
        )
    );
}

class User extends AppModel {
    public $hasMany = array(
        'SentMessages' => array(
            'className' => 'Message',
            'foreignKey' => 'from_id'
        ),
        'Messages' => array(
            'className' => 'Message',
            'foreignKey' => 'to_id'
        )
    );
}