Reputation: 1472
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?
Upvotes: 7
Views: 3632
Reputation: 48236
Get rid of the parentheses after courses
Use an arraydataprovider
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider' => new CArrayDataProvider($model->courses, array()),
'columns'=>array(
'name',
),
));
Upvotes: 13
Reputation: 15600
A few things to start off:
$model->courses
instead of $model->courses()
Anyway, I seem to remember struggling with this as well. I never really got it to work like I wanted it to. The closest I got was setting the 'data' variable in my dataProvider, but then the paging was broken in my ListView. It worked something like this:
$dataProvider=new CActiveDataProvider('Course', array(
'data'=>$model->courses,
));
What I ended up doing was creating new criteria to pass in to my DataProvider that did the same thing as the relation. Like so:
$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'm assuming that you are using a MANY_MANY relationship with a join table. I hope this helps, even though I'm sure it's not quite what you want to do. If anyone has a better solution please share! I want to learn about it too! :)
Upvotes: 0