jod*_*eci 7 cakephp unique-index cakephp-model
我有一个注册表,用户可以在其中填写两个电子邮件地址(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);
}
Run Code Online (Sandbox Code Playgroud)
Ric*_*ome 13
我在CakePHP Google Group上发布了一个解决方案:
将以下内容添加到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);
}
}
Run Code Online (Sandbox Code Playgroud)
并在您的模型验证中使用:
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"
)
)
);
Run Code Online (Sandbox Code Playgroud)
Kri*_*nck 12
checkUnique可以只写为包装isUnique.
class AppModel extends Model {
public function checkUnique($ignoredData, $fields, $or = true) {
return $this->isUnique($fields, $or);
}
}
Run Code Online (Sandbox Code Playgroud)
并在您的模型验证中使用:
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'
)
)
);
Run Code Online (Sandbox Code Playgroud)