Osuji Kingsley
Osuji Kingsley

Reputation: 371

What query can i use to get subcategories for each category?

I am using this query to get the children of each category

$this['children'] = Cat::first()->children;

But it only gets the subcategories of of the first category and the same subcategories appear for all other categories. Any ideas on how t fix this?

Model relation

 public function children(){

    return $this->hasMany(static::class,'parent_id','id');

Table structure

category table

id

cat_title

parent_id

nest_right

nest_left

nest_depth

slug

parent_id = 0(category)

parent_id > 0(subcategory)

Upvotes: 0

Views: 124

Answers (1)

Moj
Moj

Reputation: 378

To get sub-categories of each category you first need to get the id of each category and use it in you query. (e.g. in a foreach loop)

$this['children'] = Cat::find($id)->children;

If you need to get all the categories with their related subcategories at the same time you need to eager load:

$allCatsWithTheirChildren = Cat::with('children')->all();

Upvotes: 1

Related Questions