문제

사용자가 두 개의 이메일 주소 (email1 & email2)를 작성할 수있는 등록 양식이 있습니다. 마케팅의 요구 사항은 고유해야한다는 것입니다 (사용자가 10 명인 경우와 같이 고유 한 경우 10*2 = 20 고유 이메일 주소가 있습니다).

이 시스템은 이미 CakePHP를 기반으로 구축되어 있으므로 내가 알고 싶은 것은, Isunique 기능 (한 필드에서 독특한)과 비슷한 것이 있습니까? 아니면 직접 코딩 할 운명이 있습니까? 미리 감사드립니다.

편집 : Richard의 예를 바탕으로 이것은 저에게 효과적이었습니다.

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 Group에 이에 대한 솔루션을 게시했습니다.

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" 
                        ) 
                ) 
       ); 

다른 팁

checkUnique 래퍼로 쓸 수 있습니다 isUnique.

class AppModel extends Model {
    public function checkUnique($ignoredData, $fields, $or = true) {
        return $this->isUnique($fields, $or);
    }
}

모델 검증에서 사용됩니다.

public $validate = array(
    'name' => array(
        'unique' => array(
            'rule' => array('checkUnique', array('name', 'institution_id'), false), 
            'message' => 'A contact with that name already exists for that 
institution'
        )
    )
);

CakePHP 2.0 문서 :

여러 필드를 제공하고 $ 또는 false를 설정하여 필드 세트가 고유한지 확인할 수 있습니다.

public $validate = array(
    'email' => array(
        'rule' => array('isUnique', array('email', 'username'), false),
        'message' => 'This username & email combination has already been used.'
    )
);

여러 필드에서 고유 한 규칙을 만들 때 필드 목록에 원래 필드를 포함시켜야합니다.

나열된 필드가 모델 데이터에 포함되지 않으면 널 값으로 취급됩니다. 필요에 따라 나열된 필드를 표시하는 것을 고려할 수 있습니다.

예 그리고 아니오.

예, 직접 코딩해야하지만 CakePHP 검증 구성 요소 내에서 코딩해야합니다.

유효성 검사 구성 요소에는 사용자 정의 검증 규칙을 허용하는 메커니즘이 있습니다. 본질적으로, 당신은 $ validate 내에 함수 이름을 넣습니다 (평소와 같이). 함수를 정의해야합니다. 이 경우 매우 간단합니다 (이중 isunique 요구 사항 만 시행).

http://book.cakephp.org/2.0/en/models/data-validation.html#custom-validation-rules

제공하기 위해 머리와 어깨에 맞을 위험이 있습니다. 비 카세프 해결책, 다음을 제시하겠습니다.

필요한 많은 열을 통해 데이터베이스에 고유 한 색인을 만듭니다.

이에 대한 표준 SQL 구문은 다음과 같습니다.

create unique index {IndexName} on {Table} ({Column}, {Column}, ...)

"$ this-> model-> save ()"명령을 "시도/캐치"블록 안에 배치하십시오. "캐치"블록에서 오류 코드의 예외를 테스트하십시오. MySQL에서 고유 한 키 위반은 오류 코드 23000이지만 다른 가능한 오류에 대해서도 준비해야합니다.

빠르고 간단하며 배열 괄호를 계산하지 않습니다.

당신은해야합니다 언제나 어쨌든 데이터베이스 액세스 코드를 "시도/캐치"블록 안에 배치하십시오. 예외 처리의 일부에는 예기치 않은 오류 메시지 로그인이 포함되어야합니다. CakePhp가 할 것으로 기대할 수 없습니다 모든 것 당신을 위한.

내가 기억하는 한, 당신은 beforeSave 모델의 방법. 나는 객체에 n fks 중 하나 이상이 있어야한다는 요구 사항이 있었고, 이런 식으로 만 할 수있었습니다.

편집 : 시도하십시오 이 스레드 거기에 문제가 해결되는지 확인하십시오.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top