Getting associated models with $this->Auth in Cakephp

前端 未结 3 723
太阳男子
太阳男子 2021-02-20 10:07

I am using CakePHP 2.0\'s integrated Auth component. I have the following tables :

  • Users
  • Groups
  • Profiles
3条回答
  •  感动是毒
    2021-02-20 10:43

    There is no way to do this with the AuthComponent because of the way it handles the session keys. You can, however, just save it to the session yourself.

    The only way to do this is to add to the session when the user logs in:

    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());
        }
    }
    

    Then in your beforeFilter() in your AppController, save a var for the controllers to get to:

    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);
    }
    

    Update: As of CakePHP 2.2 (announced here), the AuthComponent now accepts the 'contain' key for storing extra information in the session.

提交回复
热议问题