Getting associated models with $this->Auth in Cakephp

前端 未结 3 726
太阳男子
太阳男子 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:35

    As far as I'm aware the Auth component only caches the data from your Users model. You can use that information to retrieve the desired data from the other models, by for example using this in your controller:

    $group_data = $this->Group->findById($this->Auth->user('group_id'));
    

    Or

    $profile_data = $this->Profile->findByUserId($this->Auth->user('id'));
    

    But I don't think you can get it from the Auth component directly, as it doesn't cache the related model data out of the box.

    0 讨论(0)
  • 2021-02-20 10:37

    Two ways:

    1) Extend the FormAuthenticate class (see /Controller/Component/Auth) or whatever you use to login and override the _findUser() method and tell the Auth component to use this authorize class. See this page how to do all of that http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html

    2) Simply implement a method in the model that will fetch all data you want and call it in the login method of your controller and write the data into the session. IMO it is handy to have such a method because sometimes you need to refresh the session data anyways.

    Because of your comment on the other answer:

    You will have to write a method and some code in a model that will return you the data. CakePHP can't read your mind and a database without code. No matter which of both suggested ways you're going to use, you'll have to write code.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题