Yii HAS_MANY有一些固定值

时间:2012-04-28 11:04:48

标签: php yii

我有两种型号。批次和主题。它们之间的关系是Batch HAS_MANY Subjects。问题是三个主题是MUST和所有批次。如何在模型中实现这个固定值(三个主题)?

2 个答案:

答案 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",
    );
  }
}