Search code examples
yiirelationships

Using CGridView for a model's association


I have a model with has_many association.

Let's just say Student has many Courses.

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

Something like this:

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

Also tried new CActiveDataProvider($model->courses) as dataProvider but still wont work.

Is there an easy way to do this? Or do I have to create a search criteria on the Course model with some criteria taken from the student model manually?


Solution

    1. Get rid of the parentheses after courses

    2. Use an arraydataprovider

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