Reputation: 2133
I'm playing around with the CGridView widget and I'm trying to find out if it would be appropriate to use it in the following context: Lets say I have two database tables, Car and Accident. Each car may be associated to zero or more accidents. I would like to have a column in the grid view containing the number of accidents for each car, assuming that a row in the grid view represents a car. Is this feasible using a GridView widget, or should I try some other approach?
Upvotes: 1
Views: 6319
Reputation: 1968
You can define relation for your Car model as follows:
public function relations()
{
return array(
'accidents' => array(self::HAS_MANY, 'Accidents', 'Id'),
'accidentsCount' => array(self::STAT, 'Accidents', 'AccidentId'),
);
}
If you use count($model->accidents) then you will load all related models and then use PHP count function to get number of models, if you care about performance and memory you will use stat relation accidentCount to get number of accidents.
Upvotes: 2
Reputation: 917
If you have the relation "cars have one to many accidents" a simple count on the relation can be used. $model is car here.
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'car-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'name',
array(
'header'=>'Accidents',
'value'=>'count($data->accidents)',
),
),
));
Upvotes: 1
Reputation: 8408
The easiest way is to give the car model a "getNumberOfAccidents()" getter. You can then use that in the grid as a regular column (numberOfAccidents). Easy as pie :)
Upvotes: 0