0
votes

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)

1
Can you show your Model relations and table structure?Mihir Bhende
you need to use eager load using with, Cat::with('children')->get();Farrukh Ayyaz
How do i iterate through them to get subcats belonging to each cat? cos now it gets all the cats and attached subcatsOsuji Kingsley

1 Answers

1
votes

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();