如何与经过身份验证的用户数据一起检索关联?

Chi*_*Sky 4 authentication cakephp associations cakephp-3.0

我有一个Users表和UsersProfiles表-两者有明显的关系和用户表存储基本的user_id,username,password而users_profiles表店firstname,lastname,job_title等.

在CakePHP 3中,登录时对Authentication Component的调用返回基本用户表行.我想修改相同的也返回相应的配置文件行.我怎样才能做到这一点?

我找到了一种方法 - 但我不确定是否有更优雅或更简单的方法.

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'));
        }
    }
Run Code Online (Sandbox Code Playgroud)

ndm*_*ndm 6

contain选项

在CakePHP 3.1之前,使用该contain选项

$this->loadComponent('Auth', [
    'authenticate' => [
        'Form' => [
            'contain' => ['UsersProfiles']
        ]
    ]
]);
Run Code Online (Sandbox Code Playgroud)

定制查找器

从3.1开始,您可以使用该finder选项定义用于构建获取用户数据的查询的查找程序

$this->loadComponent('Auth', [
    'authenticate' => [
        'Form' => [
            'finder' => 'auth'
        ]
    ]
]);
Run Code Online (Sandbox Code Playgroud)

在你的表类中

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

两种解决方案

将确保返回的数据AuthComponent::identify()将包含关联的数据UsersProfiles.

也可以看看