0

Hi i have on table with categories with foreign key to herself where parent_id is the same that id in this table. I want to get two arrays of objects. First with categories where

parent_id=0

and second with subcategories. But I dont know how can I catch this subcategories. I 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 and second array with subcategories i need adjust id of each object of array $category to each subcategory array. Is it possible or there are other ways?

1
  • I think you might want to look at the IN () syntax
    – RiggsFolly
    Aug 1, 2016 at 14:12

1 Answer 1

0

If you define your model relations correctly you can get categories and their subcategories in a much nicer way.

First define the 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 now get all parent categories with their subcategories the following way:

$parents = Category::whereParentId(0)->with('subcategories')->get();

This will give you list of all parent categories, each of them will have subcategories property that will store all subcategories. You can traverse them in the following way:

foreach ($parents as $parent) {
  printf("Parent category %s\n", $parent->name);

  foreach ($parent->subcategories as $subcategory) {
    printf("Subcategory %s\n", $subcategory->name);
  }
}

Small suggestion: make your parent_id nullable and store NULL for parent categories instead of 0, as 0 is not a correct category ID.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.