-2

I have three table:

categories table fields id, category_name   
subcategories table fields id, category_id, subcategory_name
child_categories table fields id, category_id, subcategory_id, child_category_name

I have three model Category, Subcategory,

1) =>category model code

class Category extends model {
   public function subcategory(){
      return $this->hasMany(Subcategory::class);
   }

   public function Child_category(){
      return $this->hasMany(Child_category::class);
   }
}

2) =>Subcategory model code

class Subcategory extends model {
   public function Category(){
      return $this->belongsTo(Category::class);
   }
}

3) =>Child_category model code

class Child_category extends model {
   public function Category(){
      return $this->belongsTo(Category::class);
   }
} 

how to make Eloquent relationship to find all data from child_categories table with related category & subcategory name?

jfadich
  • 6,110
  • 2
  • 20
  • 31
Nazmul Haque
  • 720
  • 8
  • 13

1 Answers1

1

Once the relationships are defined you can get them by simply calling the property that has the same name as the relation you need.

$category = Category::first();
$subcategory = $category->subcategory;

If you wanted to get all the categories with all subcategories and child categories in one line you can use the with() method to eagerload them efficiently.

$categories = Category::with(['subcategory', 'Child_category'])->get();

This will fetch all the categories, then fetch all the related subcategories and child categories and associate them appropriately.

jfadich
  • 6,110
  • 2
  • 20
  • 31