I have 2 tables in my Yii application; Category and Item.
Category
- id
- name
Item
- id
- category_id
- name
What I would like to do is get a list of items in Category table and subsequently count the number of items of each category in the Item table.
I'm using CActiveDataProvider to retrieve a list of items in the the Category table and then subsequently use a for-loop to count the number of items in each category. However, I can't seem to figure out how to merge the array with my DataProvider data items.
Here is my code so far.
public function actionIndex()
{
$dataProvider = new CActiveDataProvider('Category', array(
'criteria' => array(
'select' => 'id, name, slug',
'order' => 'name ASC',
),
));
$dataProvider->setPagination(false);
$count = array();
foreach($dataProvider->getData() as $categoryData) {
$count[] = Item::model()->count("category_id = :categoryID", array("categoryID" => $categoryData->id));
}
$this->render('index', array(
'dataProvider' => $dataProvider,
'count' => $count,
));
}
How do I merge the $count array with my existing dataProvider data items so that I may use it with CListView? Is there a much more better solution than this?