我有一个 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
.也可以看看
关于authentication - 如何与经过身份验证的用户数据一起检索关联?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32661318/