【问题标题】:Get user information from Model in CakePHP在 CakePHP 中从模型中获取用户信息
【发布时间】:2012-07-23 09:27:39
【问题描述】:

我刚刚学习了 CakePHP,我希望用户在编辑自己的信息时输入他们的旧密码。

在我的模型 User.php 中

'password_old' => array(
                'match_old_password' => array(
                    'rule' => 'matchOldPassword',
                    'message' => 'Wrong password'
                ),
                'minlength' => array(
                    'rule'    => array('minLength', '8'),
                    'message' => 'Minimum 8 characters long'
                )
            )

我创建了一个函数 matchOldPassword

public function matchOldPassword(){
        if($this->data['User']['password_old']==$current_password){
            return true;
        }
        return false;
}

我的问题是,如何在模型中获取当前用户密码的值?我使用的是 CakePHP 2.1。

【问题讨论】:

    标签: cakephp cakephp-2.1


    【解决方案1】:

    您可以像在控制器中一样从模型中执行数据库查询。

    所以在你的用户模型中你可以调用:

    $this->find('first', array('conditions' => array('User.id' => $userId)));
    

    $this->read(null, $userId);
    

    当然,您必须将当前用户 ID 从控制器传递给模型方法。 如果您使用的是 Cake 提供的 Auth 组件,您可以调用 $this->Auth->user('id') 来检索当前登录的用户的 id(如果这就是“当前用户”的意思)。 $this->Auth->user() 是一种控制器方法,因此不能在模型中使用。您的设置大致如下所示:

    UserModel 方法:

    public function getCurrentUserPassword($userId) {
      $password = '';
      $this->recursive = -1;
      $password = $this->read('password', $userId);
      return $password;
    }
    

    UsersController 调用:

    $userId = $this->Auth->user('id');
    $this->User->getCurrentUserPassword($userId);
    

    【讨论】:

      猜你喜欢
      • 2011-08-25
      • 2021-07-04
      • 2012-11-22
      • 1970-01-01
      • 1970-01-01
      • 2016-10-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多