1
votes

I am verymuch confused with the through relations. Here are my tables

batch (id,name)

subject(id,batch_id,name)

teacher(id,name)

subject_teacher(subject_id,teacher_id)

the relations are

batch HAS_MANY subjects

subjects BELONGS_TO batch

subject MANY_MANY teachers via subject_teacher

teachers MANY_MANY subjects via subject_teacher

No how can i specify the relation for getting

  1. Teachers of a batch
  2. Batches assigned for a teacher

i tried with a through option but it not seems to work with MANY_MANY relations. Is there any better way other than iterating through each subject?

EDIT: I know I can get the subjects of a teacher by the function in Teacher model

public function getBatches()
{
    $batches=array();
    foreach($this->subjects as $subject)
        $batches[]=$subject->batch;
    return $batches;
}

now I can get batches of a teacher by referring $teacher->batches. But I need a cleaner relation like solution so that some where in the code I can make a statement like Teacher::model()->with('batches')->findAll()

1

1 Answers

0
votes

I think it is the only way to loop through the subjects. unless you don't do it through the active record.

  //pseudo code....
  Teacher=new Teacher::model()->with('subject.batch')->find();
  subjects=Teacher->subjects;
  for(subjects as subject){
      batch=subejct->batch;
  }

The through relationship can only be applied in one-many or one-one cases, not many-many.