Using CGridView to Associate Models

I have a model with has_many association.

Let's say a student has many courses.

I would like to show all courses of a particular student using CGridView.

Something like that:

$this->widget('zii.widgets.grid.CGridView', array( 'dataProvider' => $model->courses, 'columns'=>array( 'name', ), )); 

Also tried new CActiveDataProvider($model->courses) as dataProvider, but still not working.

Is there an easy way to do this? Or do I need to create search criteria in the course model with some criteria taken from the student model manually?

+7
source share
2 answers
  • Get rid of parentheses after courses

  • Use arraydataprovider

     $this->widget('zii.widgets.grid.CGridView', array( 'dataProvider' => new CArrayDataProvider($model->courses, array()), 'columns'=>array( 'name', ), )); 
+13
source

A few things to get started:

  • I think it should be $model->courses instead of $model->courses()
  • The reason why it still doesn't work is because Yii AR relationships return an array of objects, not the actual DataProvider object

In any case, I seem to remember how I struggle with this. I never had to work as I would like. The closest I got is to set the data variable in my dataProvider, but then paging was broken in my ListView. It worked something like this:

 $dataProvider=new CActiveDataProvider('Course', array( 'data'=>$model->courses, )); 

What I ended up with was creating new criteria for my DataProvider that did the same thing as the relation. For example:

 $criteria=new CDbCriteria; $criteria->join = "JOIN student_course_relation_table sc ON sc.course_id = t.id"; $criteria->compare('sc.student_id',$model->id); $dataProvider=new CActiveDataProvider('Course', array( 'criteria'=>$model->courses, )); 

I assume that you are using a MANY_MANY relationship with a join table. Hope this helps, although I'm sure this is not exactly what you want to do. If anyone has a better solution, please share! I also want to know about it! :)

0
source

All Articles