Best Practice To Do Multiple Categories And Products

Hi,

I am newbie to yii…

I had a doubt when setting my Yii shopping cart.

What is the best approach to set a multilevel category list with the number of products in each category.

like

  1. Electronics (100),

__1. Mobile Phone (50),

__2. Tablets (20),

__3. Laptops (30)

  1. Men Clothing (200),

__1. Jeans (120),

__2. Shirts (80),

and so on.

My category table is

CREATE TABLE IF NOT EXISTS vwa_product_category (

id smallint(5) unsigned NOT NULL AUTO_INCREMENT,

name varchar(255) NOT NULL,

parent_id smallint(5) unsigned NOT NULL DEFAULT ‘0’,

image varchar(100) DEFAULT NULL,

main varchar(225) NOT NULL,

PRIMARY KEY (id),

UNIQUE KEY id (id)

) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=124 ;

and my product table have ‘parent_id’ which joints the category table.

but the parent of product can be in any level. and I am using a widget to do the process.

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>