hi have on table categories foreign key herself parent_id same id in table. want 2 arrays of objects. first categories
parent_id=0
and second subcategories. dont know how can catch subcategories. have this:
$category= category::where('parent_id', '=', 0)->get(); dd($category[0]['id']); $subcategory= category::where('parent_id', '=', (($category[0]['id']??)));
first $category shouild return me array of categories , second array subcategories need adjust id of each object of array $category each subcategory array. possible or there other ways?
if define model relations correctly can categories , subcategories in nicer way.
first define relations:
class category extends model { public function parent() { return $this->belongsto(category::class); } public function subcategories() { } return $this->hasmany(category::class, 'parent_id'); }
you can get parent categories subcategories following way:
$parents = category::whereparentid(0)->with('subcategories')->get();
this give list of parent categories, each of them have subcategories property store subcategories. can traverse them in following way:
foreach ($parents $parent) { printf("parent category %s\n", $parent->name); foreach ($parent->subcategories $subcategory) { printf("subcategory %s\n", $subcategory->name); } }
small suggestion: make parent_id nullable , store null parent categories instead of 0, 0 not correct category id.
Comments
Post a Comment