开发者

mySQL query for getting cascading items count in categories table

开发者 https://www.devze.com 2023-03-03 17:12 出处:网络
I have a categories tree table id, parent_id, name, count and other tables that are connected trough category_id that are irrelevant now..

I have a categories tree table

id, parent_id, name, count

and other tables that are connected trough category_id that are irrelevant now..

with various queries I get the count (products, users, news, etc) for all categories.

lets say I have a root category ELECTRONICS that has some first level children (TVs, PHOTOCAMERAS, COMPUTERS). Each of them have some more sub categories...

ELECTRONICS
    - TVs
        * LCD
        * Plasma
        * CRT
    - PHOTOCAMERAS
        * DSLR
        * Compact
    - COMPUTERS
        * Laptops
        * Desktops
        * Netbooks

etc...

Now I can count number of products for a specific category... What I'd like to accomplish is to populate counts for the parents categories!

so If开发者_运维技巧 I have 3 products for Plasma TVs and 5 products for LCD TVs and 2 products for CRTs.. the count for TVs should be 10.

So I am struggling with the counting logic... I know I should count from the deepest level up, but how do I do that? What is the correct PHP code for this?

The only thing I have is the CATS array of all categories rows formatted like this:

$CATS = array(
    [cat_id] => array(id, parent_id, name, count),
    [cat_id] => array(id, parent_id, name, count),

);


May be a nested set better fits your needs.

0

精彩评论

暂无评论...
验证码 换一张
取 消