【问题标题】:CakePHP custom Validation rule checks unique field combination only on createCakePHP 自定义验证规则仅在创建时检查唯一字段组合
【发布时间】:2013-12-03 16:50:18
【问题描述】:

我有一个带有用户模型的数据库。这些用户的姓名和生日应该是唯一的。 所以我写了一个自定义的校验函数叫做 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",为什么它也会在更新时触发? 第二个问题: 如果验证规则仅在创建时触发,如果有人像数据库中的其他用户一样更改姓名、姓氏和生日,我该如何管理以触发验证错误?然后应该触发唯一的验证规则。

【问题讨论】:

    标签: validation cakephp unique updatemodel


    【解决方案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);
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-01
    • 2011-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多