我不明白如何选择登录后保存哪些用户数据。我注意到我只能更改模型的递归性,但无法选择要使用的单个字段。
例如,通常 Cakephp 会在会话中保存除密码之外的所有用户字段,甚至是我不需要且不想存储的数据。 如果我增加递归,Cakephp 会保存相关模型的所有字段。
模型查找方法的“fields”参数有办法吗?
我知道登录后我可以恢复丢失的数据并将它们添加到会话中,合并到已存储的数据,但我想避免进行另一个查询并找到更优雅的解决方案(如果存在)。
谢谢。
从 Cake 2.2 开始,您可以在身份验证选项中添加
contain
键来提取相关数据。由于 contain
键接受 fields
键,因此您可以限制那里的字段:
public $components = array(
'Auth' => array(
'authenticate' => array(
'Form' => array(
'contain' => array(
'Profile' => array(
'fields' => array('name', 'birthdate')
)
)
)
)
)
);
如果您想更改用户模型搜索的字段,您可以扩展您正在使用的身份验证对象。通常,用户表包含最少量的信息,因此通常没有必要。
不过,我还是举个例子。我们将在这里使用 FormAuthenticate 对象,并使用 BaseAuthenticate 类中的大部分
_findUser
方法代码。这是Cake的认证系统用来识别用户的功能。
App::uses('FormAuthenticate', 'Controller/Component/Auth');
class MyFormAuthenticate extends FormAuthenticate {
// overrides BaseAuthenticate::_findUser()
protected function _findUser($username, $password) {
$userModel = $this->settings['userModel'];
list($plugin, $model) = pluginSplit($userModel);
$fields = $this->settings['fields'];
$conditions = array(
$model . '.' . $fields['username'] => $username,
$model . '.' . $fields['password'] => $this->_password($password),
);
if (!empty($this->settings['scope'])) {
$conditions = array_merge($conditions, $this->settings['scope']);
}
$result = ClassRegistry::init($userModel)->find('first', array(
// below is the only line added
'fields' => $this->settings['findFields'],
'conditions' => $conditions,
'recursive' => (int)$this->settings['recursive']
));
if (empty($result) || empty($result[$model])) {
return false;
}
unset($result[$model][$fields['password']]);
return $result[$model];
}
}
然后使用该身份验证并通过我们的新设置:
public $components = array(
'Auth' => array(
'authenticate' => array(
'MyForm' => array(
'findFields' => array('username', 'email'),
'contain' => array(
'Profile' => array(
'fields' => array('name', 'birthdate')
)
)
)
)
)
);
我刚刚花了一段时间解决这个问题,结果发现从 Cake 2.6 开始已经实现了 'userFields' 选项
查看此处的文档: http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html