Yii模型按关系条件过滤的范围

时间:2014-10-24 19:23:06

标签: mysql yii

我的模型组与HAS_MANY的关联ScheduleElement。 需要创建过滤组的范围: 对于字段的所有组合,组必须具有最小值ScheduleElement ScheduleElement' s:weeknumber(1-2),week_day(1-7),semester_id = 1

1 个答案:

答案 0 :(得分:1)

我自己找到解决方案,源代码:https://github.com/sc0rp1d/schedule/blob/e510ad72b95e9491af9ff2f5692d9b0e469140f7/models/Group.php#L95

public function filled($bool = true)
    {
    $schedule_table = ScheduleElement::model()->tableName();
    $semester = Semesters::model()->actual();
    $criteria = $this->getDbCriteria();
    $criteria->params[':semester_id'] = $semester->id;
    for ($i = 1; $i <= 2; $i++) {
        for ($j = 1; $j <= 6; $j++) {
            $sql = "(SELECT COUNT(*) FROM `$schedule_table` 
                WHERE `$schedule_table`.`week_number` = $i 
                AND `$schedule_table`.`week_day` = $j 
                AND `$schedule_table`.`group_id` = `t`.`id` 
                AND `$schedule_table`.`semester_id` = :semester_id) " 
                . ($bool ? ">" : "=") . " 0";
            $criteria->addCondition($sql, $bool ? 'AND' : 'OR');
        }
    }
    return $this;
}