德塞兹和查普曼是对的。我从 cakephp 食谱的数据验证章节中找到了解决方案。非常感谢你们。
以下是我添加的验证规则:
对于学生模型中的学生姓名:
var $validate=array(
'name'=>array(
'nameRule1'=>array(
'rule'=>array('minLength',3),
'required'=>true,
'allowEmpty'=>false,
'message'=>'Name is required!'
),
'nameRule2'=>array(
'rule'=>'isUnique',
'message'=>'Student name with the same parent name already exist!'
)
),
然后在StudentController的add函数中:
//checking to see if parent already exist in merry_parents table when siblings or twin are admitted.
$merry_parent_id=$this->Student->MerryParent->getMerryParentId($this->data['MerryParent']['email']);
if (isset($merry_parent_id)){
$this->data['Student']['merry_parent_id']=intval($merry_parent_id);
var_dump($this->data['Student']['merry_parent_id']);
if ($this->Student->save($this->data)){
//data is saved only to Students table and not merry_parents table.
$this->Session->setFlash(__('Your child\'s admission has been received.
We will send you an email shortly.',true));
}else
$this->Session->setFlash(__('Your admission could not be saved. Please, try again.',true));
}else{//New record. So, data is saved to Students table and merry_parents table.
if ($this->Student->saveAll($this->data)){ //save to students table and merry_parents table
$this->Session->setFlash(__('Your child\'s admission has been received.
We will send you an email shortly.',true));
}else
$this->Session->setFlash(__('Your admission could not be saved. Please, try again.', true));
}//new record end if
正如查普曼所说,我无需在不保存的情况下验证数据。所以,我没有使用:
if ($this->Model->validates() ) {
save
} else {
error message / redirect
}