CakePHP自定义验证规则仅在创建时检查唯一字段组合

 nancy 发布于 2023-02-13 10:29

我有一个用户模型的数据库.这些用户的名字和生日应该是唯一的.所以我写了一个名为checkUnique的自定义验证函数

public function checkUnique($check){
        $condition = array(
            "User.name" => $this->data["User"]["name"],
            "User.lastname" => $this->data["User"]["lastname"],
            "User.birthday" => $this->data["User"]["birthday"]
        );

        $result = $this->find("count", array("conditions" => $condition));

        return ($result == 0);
}

模型中的验证规则:

"name" => array(
       "checkUnique" => array(
            "rule" => array("checkUnique"),
            "message" => "This User already exists.",
            "on" => "create"
       ),
)

我有两个问题.第一种:此验证规则也会在更新操作时触发,实现为

public function edit($id = null) {
        if (!$this->User->exists($id)) {
            throw new NotFoundException(__('Invalid User'));
        }
        if ($this->request->is(array('post', 'put'))) {
            if ($this->User->save($this->request->data)) {
                $this->Session->setFlash(__('Update done.'));
                return $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The user can't be saved.'));
            }
        } else {
            $options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
            $this->request->data = $this->User->find('first', $options);
        }
    }

但我写了"on" => "create",为什么它也会在更新时触发?第二个问题:如果验证规则只触发上创建的,我怎么能管理,触发验证错误,如果有人改名换姓,姓和生日与数据库中的另一用户?然后应该触发唯一的验证规则.

1 个回答
  • 删除'on'=>'create'.(您希望在两个事件中都进行验证).

    将自定义验证规则修改为此

    public function checkUnique() {
        $condition = array(
            "User.name" => $this->data["User"]["name"],
            "User.lastname" => $this->data["User"]["lastname"],
            "User.birthday" => $this->data["User"]["birthday"]
        );
        if (isset($this->data["User"]["id"])) {
            $condition["User.id <>"] = $this->data["User"]["id"];
            //your query will be against id different than this one when 
            //updating 
        }
        $result = $this->find("count", array("conditions" => $condition));
        return ($result == 0);
    }
    

    2023-02-13 10:33 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有