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

标签 authentication cakephp associations cakephp-3.0

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

在 CakePHP 3 中,登录时对身份验证组件的调用返回基本的用户表行。我想修改它以返回相应的配置文件行。我怎样才能做到这一点?

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

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

最佳答案

contain选项

在 CakePHP 3.1 之前,使用 contain选项

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

自定义查找器

从 3.1 开始,您可以使用 finder用于定义用于构建获取用户数据的查询的查找器的选项
$this->loadComponent('Auth', [
    'authenticate' => [
        'Form' => [
            'finder' => 'auth'
        ]
    ]
]);

在你的餐 table 课上
public function findAuth(\Cake\ORM\Query $query, array $options)
{
    return $query->contain(['UsersProfiles']);
}

两种解决方案

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

也可以看看
  • Cookbook > ... Components > Authentication > Configuring Authentication Handlers
  • Cookbook > ... Components > Authentication > Customizing find query
  • 关于authentication - 如何与经过身份验证的用户数据一起检索关联?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32661318/

    相关文章:

    ruby-on-rails - 我无法使用accepts_nested_attributes_for 创建模型对象。它不会创建嵌套对象

    ruby-on-rails - 如何摆脱归因于 rails 关联的 n+1 查询?

    php - Android phonegap 使用本地 html 和远程 php 登录

    amazon-web-services - AWS - Cognito 联合身份

    cakephp - CakePHP 中的 TCPDF 奇怪问题

    ruby - 如何从 Rake 文件、Make 文件或它们的组合调用 Cake 文件?

    php - 从 CakePHP 中的 saveAll() 检索插入的 ID

    ruby-on-rails - Rails 2.3 基于其他关联的动态 has_many 条件

    authentication - 应用权限和oauth2授权有什么区别?

    api - RESTful API 身份验证/安全