Cakephp:选择登录后要保存的数据

时间:2012-10-24 13:22:48

标签: session cakephp login

我无法理解如何选择登录后要保存的用户数据。我注意到我只能改变模型的递归性,但我不能选择单独的字段来使用。

例如,通常Cakephp会在会话中保存除密码以外的所有用户字段,甚至是我不需要的数据,我也不想存储。 如果我增加递归,Cakephp会保存相关模型的所有字段。

对于Model find方法的“fields”参数有没有办法?

我知道登录后我可以恢复我想念的数据并将它们添加到会话中,合并到那些已存储的数据,但是我想避免再进行查询并找到更优雅的解决方案(如果存在的话)。

感谢。

2 个答案:

答案 0 :(得分:2)

从Cake 2.2开始,您可以在身份验证选项中添加contain密钥以提取相关数据。由于contain键接受fields键,因此您可以限制其中的字段:

public $components = array(
  'Auth' => array(
    'authenticate' => array(
      'Form' => array(
        'contain' => array(
          'Profile' => array(
            'fields' => array('name', 'birthdate')
          )
        )
      )
    )
  )
);

如果要更改用户模型搜索的字段,可以扩展您正在使用的身份验证对象。通常,users表包含最少量的信息,因此通常不需要这样做。

但是,无论如何,我会给出一个例子。我们将在此处使用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')
          )
        )
      )
    )
  )
);

答案 1 :(得分:0)

我只是花了一些时间来解决这个问题,但却发现从Cake 2.6开始实现'userFields'选项

在这里查看文档: http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html