答案 0 :(得分:1)
如果您确实不想在数据库中存储3个默认主题,则可以编写一个函数,该函数返回默认主题以及与Batch对象实际相关的任何主题。
假设您的关系被称为“主题”:
class Batch extends CActiveRecord
{
...
public function getAllSubjects()
{
$subject1 = new Subject;
...
$subject2 = new Subject;
...
$subject3 = new Subject;
...
return array($subject1, $subject2, $subject3) + $this->subjects;
}
限制是您无法在数据库条件中引用默认主题,并且您必须确保使用$model->allSubjects
而不是$model->subjects
答案 1 :(得分:0)
使用自定义验证器。这应该有用,虽然没有经过测试。
class RelatedObjAttrRangeValidator extends CValidator {
public $relationName;
public $relatedObjectAttributeName;
public $relatedObjectValues = array();
public function validateAttribute($object, $attribute) {
if(!$this->relationName) {
$this->relationName = $attribute;
}
if(!$this->relatedObjectAttributeName || !count($this->relatedObjectValues)) {
throw new CException("Misconfigured Validator!");
}
$relatedObjects = $object->getRelated($this->relationName);
if(is_array($relatedObjects)) {
$unmatched = array_values($this->relatedObjectValues);
$attr = $this->relatedObjectAttributeName;
foreach($relatedObjects as $relObj) {
$val = $relObj->$attr;
$idx = array_search($val, $unmatched);
if($idx !== -1) {
unset($unmatched[$idx]);
}
if(!count($unmatched)) {
break;
}
}
if(count($unmatched)) {
$object->addError($attribute, $this->message);
}
} else {
throw new CException(Yii::t('error', 'Relation {rel} in model {model} is not an array!', array(
'{rel}' => $this->relationName,
'{model}' => get_class($model),
));
}
}
}
class Batch extends CActiveRecord {
public function rules() {
return array(
array('subjects', 'RelatedObjAttrRangeValidator',
'relatedObjectAttributeName' => 'ID',
'relatedObjectValues' => array("required_id_1", "required_id_2", "required_id_3"),
'message' => "One or more required Subjects are missing",
);
}
}