在Cakephp中使用$ this-> Auth获取关联模型

AnN*_*LaI 11 cakephp cakephp-2.0

我正在使用CakePHP 2.0的集成Auth组件.我有以下表格:

  • 用户
  • 简介

我的模型关系如下:

User belongsTo Group
User hasMany Profiles
Run Code Online (Sandbox Code Playgroud)

登录到站点后,我注意到Auth会话仅包含用户表信息,但我也需要登录用户的组和配置文件表的信息.

有没有办法用Auth组件做到这一点?

jer*_*ris 6

AuthComponent因为它处理会话密钥的方式,所以无法做到这一点.但是,您可以自己将其保存到会话中.

执行此操作的唯一方法是在用户登录时添加到会话中:

function login() {
    if ($this->Auth->login($this->data)) {
        $this->User->id = $this->Auth->user('id');
        $this->User->contain(array('Profile', 'Group'));
        $this->Session->write('User', $this->User->read());
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在你的beforeFilter()in中AppController,为控制器保存一个var,以便:

function beforeFilter() {
    $this->activeUser = $this->Session->read('User');
}

// and allow the views to have access to user data
function beforeRender() {
    $this->set('activeUser', $this->activeUser);
}
Run Code Online (Sandbox Code Playgroud)

更新:从CakePHP 2.2(此处公布)开始,AuthComponent现在接受"包含"键以在会话中存储额外信息.