How do I get all products of a “main category” if a product is related to only one “subcategory”? A product is only related to a sub-category, while a sub-category is always part of the main category. So I want to have all products in the main category. A query like the below would not work or return no products because no product is related to category #1.
Categories::where(['id' => 1])->products();
Models/Category.php
public function parent(): BelongsTo
{
return $this->belongsTo(Category::class, 'parent_id');
}
public function children(): HasMany
{
return $this->hasMany(Category::class, 'parent_id');
}
Models/Product.php
public function category(): BelongsTo
{
return $this->belongsTo(Category::class);
}
What do I need to do/change to get all products of the main category (preferably without checking if the category with ID #1 is the main category)?