Support the ongoing development of Laravel.io →
posted 10 years ago
Database
Last updated 2 years ago.
0

Your category table should be like this: id, parent_id, category_name. Whereas parent_id shows where that category is. For example:

id, parent_id, category_name

1,0,Category 1

2,1,category 1.1

3,2,category 1.1.1

4,0,Category 2

5,4,category 2.1

6,5,category 2.1.1

Every cat. has its unique id, and its parent's id (if its 0 there is no parent)

With this structure if you add a new sub-cat. under "Category 1", sub-cat. gets 7 as id, and also gets 1 as parent_id.

Last updated 2 years ago.
0

Thanks, so in my Category model i should write something like this:

    public function subcats()
    {
        return $this->belongsToMany('Category', 'parent_id');
    }

that's it?

Last updated 2 years ago.
0

I'm new at Laravel, so I'm not sure about that :) But the algorithm is OK :)

Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.