In my database, I have a Categories table. Categories can have parent categories, making it a recursive relationship
I also have a products table. Each product falls
This way works very good:
class One extends Model {
public function children()
{
return $this->hasMany(self::class, 'parent_id');
}
public function grandchildren()
{
return $this->children()->with('grandchildren');
}
}
After hoping to find an answer that uses Laravel nicely, I ended up giving up and just writing the code to do what I wanted myself, and it ended up smaller than I anticipated.
public function all_products()
{
$products = [];
$categories = [$this];
while(count($categories) > 0){
$nextCategories = [];
foreach ($categories as $category) {
$products = array_merge($products, $category->products->all());
$nextCategories = array_merge($nextCategories, $category->children->all());
}
$categories = $nextCategories;
}
return new Collection($products); //Illuminate\Database\Eloquent\Collection
}
Suppose your Model name is Category
Create a function on Category model
public function children() { return $this->hasMany('App\Category', 'parent_id', 'id'); }
Using above method on your controller
$categories = Category::with('children')->where('parent_id',0)->get();
you better use nested sets models. you should use this data structure due to get fastest way to query in mysql with a simple way. with just a parent_id attribute,you don't know how deep your tree is and this make problem in knowing how many join you need. I offer you this excellent article. managing-hierarchical-data-in-mysql
for those who use laravel framework, I prefer to suggest this amazing package:Baum
Say $category_id = Category->id and you want a collection of products as children of that category, I would try:
$products = App\Product::with(['SubSubCategory.SubCategory.Category'=>function($query) use ($category_id) {$query->where('id', $category_id);}])->get();
To be able to do so. You will need your 'one to many' inverse relationships to be as such:
//App\SubCategory
public function Category(){return $this->belongsTo('App\Category');}
//App\SubSubCategory
public function Sub_Category(){return $this->belongsTo('App\SubCategory');}
//App\Product
public function SubSubCategory(){return $this->belongsTo('App\SubSubCategory');}
Good luck.
please try the below Has Many Through relation and post the result
class Category extends Model
{
public function products()
{
return $this->hasManyThrough(
'App\Product', 'App\Category',
'parent_id', 'catergory_id', 'id'
);
}
}
Then you can use $category->products;
to find your products