The name of column that join the product & category tables must be ‘category_id’ not ‘parent_id’.
'category' table:
-----------------
id
name
parent_id //refers to the category itself
image
main
'product' table:
-----------------
id
category_id // the foreign key that join two tables
parent_id //refers to the product itself
.
.
.
In this case you can join two tables together:
// in the Category's model class
class Category extends CActiveRecord
{
public function relations()
{
return array(
'products' => array(self::HAS_MANY, 'Product', 'category_id'),
'productsCount' => array(self::STAT, 'Products', 'category_id'),
);
}
//other code
}
// in the Category's controller class (for example list action method)
class CategoryController extends CController
{
public function actionList()
{
$models = Category::model()->with('productsCount')->findAll();
$this->render('list', array('models'=>$models));
}
}
// in the view file (for example list.php)
<div class="category-list">
<?php
foreach($models as $model)
{
echo('<p class="cat-item">'$model->name.'('.$model->productsCount.')</p>');
}
?>
</div>