我有两个模型。批次和主题。它们之间的关系是 Batch HAS_MANY Subjects。问题是三个主题是必须的,并且适用于所有批次。我如何在模型中实现这个固定值(三个主题)?
问问题
305 次
2 回答
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
于 2012-04-29T02:24:32.733 回答
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",
);
}
}
于 2012-04-28T11:36:48.777 回答