我有一个注册表,用户可以在其中填写两个电子邮件地址(email1和email2)。市场营销的要求是它们必须是唯一的(就像我们有10个用户那样唯一,那么将有10 * 2 = 20个唯一的电子邮件地址)。

该系统已经建立在cakephp上,所以我想知道的是,是否存在类似于isUnique功能(在一个字段中唯一)可以立即执行此操作的功能?还是我注定要自己编写代码?提前致谢。

编辑:建立在理查德的例子上,这对我有用:

function checkUnique($data, $fields) {
    if (!is_array($fields)) {
        $fields = array($fields);
    }
    foreach($data as $key) {
        $checks = $key;
    }
    if (empty($checks)) {
      return true;  //allow null
    }
    foreach($fields as $key) {
        $tmp[$key] = $checks;
    }
    if (isset($this->data[$this->name][$this->primaryKey])) {
        $tmp[$this->primaryKey] = "<>".$this->data[$this->name][$this->primaryKey];
    }
    return $this->isUnique($tmp);
}

最佳答案

我在CakePHP Google组上发布了一个解决方案:

http://groups.google.com/group/cake-php/browse_frm/thread/b3a1e4ae3eeb6091/e168f54bac27c163?lnk=gst&q=checkUnique#e168f54bac27c163

将以下内容添加到您的AppModel中:

        /**
         * checks is the field value is unqiue in the table
         * note: we are overriding the default cakephp isUnique test as the
original appears to be broken
         *
         * @param string $data Unused ($this->data is used instead)
         * @param mnixed $fields field name (or array of field names) to
validate
         * @return boolean true if combination of fields is unique
         */
        function checkUnique($data, $fields) {
                if (!is_array($fields)) {
                        $fields = array($fields);
                }
                foreach($fields as $key) {
                        $tmp[$key] = $this->data[$this->name][$key];
                }
                if (isset($this->data[$this->name][$this->primaryKey])) {
                        $tmp[$this->primaryKey] = "<>".$this->data[$this->name][$this-
>primaryKey];

                }
                return $this->isUnique($tmp, false);
        }
}

并用于模型验证中:
        var $validate = array(
                "name"=>array(
                        "unique"=>array(
                                "rule"=>array("checkUnique", array("name", "institution_id")),
                                "message"=>"A contact with that name already exists for that
institution"
                        )
                )
       );

关于cakephp isUnique有2个字段吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2461267/

10-16 07:32