Home > Blockchain >  Laravel get all products from parent category or subcategory using eloquent
Laravel get all products from parent category or subcategory using eloquent

Time:02-17

I would like to retrieve all products of chosen parent category.Product model have hasmany relation to product_category_mapping table.

If product have subcategory result like,

"MAinCatergory":[
    {
        id="",
        name:"Drinks",
        "ChildCategory":[
            {
                "id":1,
                "name":"Juce",
                "Products":[{
                   name:"apple juce",
                   price:10,
                    ....
               }]
            }
        ]
    }
]

}

If product under main category only return array like,

"MAinCatergory":[
    {
        id="",
        name:"Drinks",
                "Products":[{
                   name:"apple juce",
                   price:10,
                    ....
               }]
            }
    }
]

}

category table fields - id,name,parent_id

product table fields - id,name,price,..,

product-category-mapping table fields - id,category_id,product_id

category model

public function children()
{
  return $this->hasMany('App\Models\Category', 'parent_id');
}
public function parent()
{
  return $this->belongsTo('App\Models\Category', 'parent_id');
}
public function product_category()
{
  return $this->hasMany('App\Models\ProductCategoryMapping', 'category_id');
}

product model

public function product_category()
{
    return $this->hasMany('App\Models\ProductCategoryMapping','product_id');
}

product-category_mapping

public function product()
{
  return $this->belongsTo(Product::class,'product_id','id');
}
public function category()
{
  return $this->belongsTo(Category::class,'category_id','id');
}

CodePudding user response:

Something like this might suffice.

App\Models\Category::with('children', 'product_category.product')->get()

Suggestion, try implement pivot many to many relation instead this product_category_mapping, then model relation would change a bit.

For pivot relation, you need to modify the Category model

public function products()
{
  return $this->belongsToMany('App\Models\Product', 'product-category-mapping');
}

and in product Model

public function categories()
{
    return $this->belongsToMany('App\Models\Category','product-category-mapping');
}

This is not the complete integration, but to give you an idea, for full logic see https://laravel.com/docs/9.x/eloquent-relationships#many-to-many

CodePudding user response:

in your product model add like this:

public function product_categorys(){

    return $this->hasMany('App\Models\ProductCategoryMapping','product_id');
} 

and in controller you can get inside your function like this Product::with('product_categorys')->get();

  • Related