afterFind上的多个字段

时间:2018-07-03 21:10:01

标签: php cakephp cakephp-appmodel

我有cakephp应用程序模型,在其中需要解密两个字段。为此,我使用afterFind回调。效果很好,但是当我在$ encryptedFields中添加第二个字段时,解密只会执行一个字段。

我的回调代码如下:

public $encryptedFields = array('name', 'details');


public function beforeSave($options = array()) {
    foreach($this->encryptedFields as $fieldName){
        if(!empty($this->data[$this->alias][$fieldName])){
            $k = 'wt1U5MACWJFTXGenFoZoiLwQGrLgdbHA';
            $this->data[$this->alias][$fieldName] = Security::encrypt($this->data[$this->alias][$fieldName], $k);
        }                                           
    }
    return true;
}



public function afterFind($results, $primary = false) {
    foreach($this->encryptedFields as $fieldName){
        foreach ($results as $key => $val) {
            if (isset($val[$this->alias][$fieldName])) {
                $k = 'wt1U5MACWJFTXGenFoZoiLwQGrLgdbHA';
                $results[$key][$this->alias][$fieldName] = Security::decrypt($val[$this->alias][$fieldName], $k);
            }
        }
        return $results;
       }

}

出于说明目的,我已经在beforeSave中包含了加密功能,但是这样做很好并且可以对两个字段进行加密,就像之前所说的那样,我的问题似乎与afterFind $ results有关,但是我没有主意。谁能帮我吗?

1 个答案:

答案 0 :(得分:1)

问题在于,您需要从return循环中foreach遍历$encryptedFields数组中的每个项目。将return $results;移出foreach循环,您应该能够解密两个字段。

public function afterFind($results, $primary = false) {
    foreach($this->encryptedFields as $fieldName){
        foreach ($results as $key => $val) {
            if (isset($val[$this->alias][$fieldName])) {
                $k = 'wt1U5MACWJFTXGenFoZoiLwQGrLgdbHA';
                $results[$key][$this->alias][$fieldName] = Security::decrypt($val[$this->alias][$fieldName], $k);
            }
        }
    }
    return $results; // move this here
}