2012-10-24 37 views
0

我無法理解如何選擇登錄後保存哪些用戶數據。我注意到,我只能改變模型的遞歸性,但我不能選擇單個字段來使用。Cakephp:登錄後選擇要保存哪些數據

例如,通常Cakephp會保存會話中除密碼之外的所有用戶字段,即使是我不需要的數據,也不需要存儲。 如果我增加遞歸,Cakephp保存所有相關模型的字段。

模型查找方法的「fields」參數有沒有辦法?

我知道,登錄後我可以恢復我錯過的數據,並將它們添加到會話中,合併到已存儲的數據中,但我想避免再次進行查詢並找到更優雅的解決方案(如果存在)。

謝謝。

+0

您正在使用什麼版本的蛋糕? – jeremyharris

+0

最新版本,2.2.3。 –

回答

2

從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') 
     ) 
     ) 
    ) 
    ) 
) 
); 
+0

非常感謝。 –