Hi guys,
I would like to have an advice about the following situation:
I have two tables with a relation: Deposit and Items.
To show the list of deposits I’m using a CGridView widget, and now
I would add the number of items that belong to a deposit.
Can anyone explain me how can I do that please?
Thanks,
Regards
Bizley
(Bizley)
October 7, 2014, 9:16am
2
Create relation with counter in your Deposit model:
public function relations()
{
return array(
'itemCount' => array(self::STAT, 'Items', 'deposit_id'),
);
}
Add this in your search method:
$criteria->with = array('itemCount');
Now in your CGridView add column:
'columns' => array(
array(
'name' => 'itemCount',
'value' => '$data->itemCount',
),
),
Bizley,
it works, thank you for your advice.
I would ask you now, could be possible the same thing with a field that is not an id?
For example, I have a field which contains string, so I would count the rows with the same string.
I’ve tried to replace ‘deposit_id’ with ‘deposit_name’, but it doesn’t work.
Thanks
Bizley
(Bizley)
October 7, 2014, 10:20am
4
Do you mean you want to count all rows where certain field is ‘some_string’?
Bizley
(Bizley)
October 7, 2014, 10:41am
6
You can use CActiveRecord::count for this, like Model::model()->count(’field
= :query’, array(’:query’ => $string)) or CActiveRecord::countByAttributes like Model::model()->countByAttributes(array(‘field’ => $string)).