Authentication 如何与经过身份验证的用户数据一起检索关联?
我有一个Authentication 如何与经过身份验证的用户数据一起检索关联?,authentication,cakephp,associations,cakephp-3.0,Authentication,Cakephp,Associations,Cakephp 3.0,我有一个Users表和一个UsersProfiles表-这两个表显然是相关的,用户表存储基本的userid,username,password,而Users\u profiles表存储firstname,lastname,job\u title等 在CakePHP3中,登录时对身份验证组件的调用返回基本用户表行。我想对其进行修改,以同时返回相应的配置文件行。我该怎么做 我找到了一种方法,但不确定是否有更优雅或更简单的方法 public function login() { if
Users
表和一个UsersProfiles
表-这两个表显然是相关的,用户表存储基本的userid
,username
,password
,而Users\u profiles表存储firstname
,lastname
,job\u title
等
在CakePHP3中,登录时对身份验证组件的调用返回基本用户表行。我想对其进行修改,以同时返回相应的配置文件行。我该怎么做
我找到了一种方法,但不确定是否有更优雅或更简单的方法
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'));
}
}
包含
选项
在CakePHP3.1之前,请使用contain
选项
$this->loadComponent('Auth', [
'authenticate' => [
'Form' => [
'contain' => ['UsersProfiles']
]
]
]);
自定义查找器
从3.1开始,您可以使用finder
选项定义用于构建获取用户数据的查询的finder
$this->loadComponent('Auth', [
'authenticate' => [
'Form' => [
'finder' => 'auth'
]
]
]);
在你的桌子课上
public function findAuth(\Cake\ORM\Query $query, array $options)
{
return $query->contain(['UsersProfiles']);
}
两种解决方案
将确保由AuthComponent::identify()
返回的数据将包含关联的UsersProfiles
另见