下面是我認爲現在最好的。它使用cakephp 3.x行爲進行HABTM驗證。
我選擇只在模型中使用最普通的代碼。
在你AppModel.php
,設置此beforeValidate()
和afterValidate()
class AppModel extends Model {
/** @var array set the behaviour to `Containable` */
public $actsAs = array('Containable');
/**
* copy the HABTM post value in the data validation scope
* from data[distantModel][distantModel] to data[model][distantModel]
* @return bool true
*/
public function beforeValidate($options = array()){
foreach (array_keys($this->hasAndBelongsToMany) as $model){
if(isset($this->data[$model][$model]))
$this->data[$this->name][$model] = $this->data[$model][$model];
}
return true;
}
/**
* delete the HABTM value of the data validation scope (undo beforeValidate())
* and add the error returned by main model in the distant HABTM model scope
* @return bool true
*/
public function afterValidate($options = array()){
foreach (array_keys($this->hasAndBelongsToMany) as $model){
unset($this->data[$this->name][$model]);
if(isset($this->validationErrors[$model]))
$this->$model->validationErrors[$model] = $this->validationErrors[$model];
}
return true;
}
}
在此之後,您可以使用您的驗證在你的模型是這樣的:
class Post extends AppModel {
public $validate = array(
// [...]
'Tag' => array(
// here we ask for min 1 tag
'rule' => array('multiple', array('min' => 1)),
'required' => true,
'message' => 'Please select at least one Tag for this Post.'
)
);
/** @var array many Post belong to many Tag */
public $hasAndBelongsToMany = array(
'Tag' => array(
// [...]
)
);
}
這個答案用途: