How to retrieve associations together with authenticated user data?

风格不统一 提交于 2019-11-30 05:58:26

问题


I have a Users table and a UsersProfiles table - the two are obviously related and the user table stores basic user_id, username, password while the users_profiles table stores firstname, lastname, job_title etc.

In CakePHP 3, the call to Authentication Component on login returns the basic user table row. I would like to modify the same to also return the corresponding profile row. How can I do this?

I found a way to do it - but am not sure if there is a more elegant or simpler way.

public function login() {
        if ($this->request->is('post')) {
            $user = $this->Auth->identify();
            if ($user) {
                // load profile and associate with user object
                $profile = $this->Users->UsersProfiles->get($user['id']);
                $user['users_profile'] = $profile;
                $this->Auth->setUser($user);
                return $this->redirect($this->Auth->config('loginRedirect'));
            }
            $this->Flash->error(__('Invalid username or password, try again'));
        }
    }

回答1:


The contain option

Before CakePHP 3.1, use the contain option

$this->loadComponent('Auth', [
    'authenticate' => [
        'Form' => [
            'contain' => ['UsersProfiles']
        ]
    ]
]);

A custom finder

As of 3.1 you can use the finder option to define the finder to use for building the query that fetches the user data

$this->loadComponent('Auth', [
    'authenticate' => [
        'Form' => [
            'finder' => 'auth'
        ]
    ]
]);

In your table class

public function findAuth(\Cake\ORM\Query $query, array $options)
{
    return $query->contain(['UsersProfiles']);
}

Both solutions

will ensure that the data returned by AuthComponent::identify() will contain the associated UsersProfiles.

See also

  • Cookbook > ... Components > Authentication > Configuring Authentication Handlers
  • Cookbook > ... Components > Authentication > Customizing find query


来源:https://stackoverflow.com/questions/32661318/how-to-retrieve-associations-together-with-authenticated-user-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!