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

3
我有一个数据库和一个用户模型。这些用户应该根据他们的姓名和生日是唯一的。 因此,我编写了一个名为 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个回答

7

将 '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);
}

1
更正:$condition ["User.id <>"] = $this->data["User"]["id"]; - MotsManish
感谢您的回答,它对我很有帮助! - TommyDo
能否在这里帮我一下,@Guillemo Mansilla https://stackoverflow.com/questions/50771575/cakephp-3-2-unique-validator - Sanjay Kumar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接