@drewdan if you define your relationship between Products and Categories
Product
function categories(){
return $this->belongsToMany(Category::class)
}
and in Category
function products(){
return $this->belongsToMany(Product::class)
}
then you'll be able to get the following
- all categories this product is in
$product->categories();
- all products that are in this category.
$category->products();
your relationship has 1 join table between your products & your categories. its not really necessary to make a specific model for this, or define any relationships on that model.
hasManyThrough Eloquent relationship is more complex and uses three database tables.
Upper level table has relationship with many rows of middle level table and middle level table has relationship with many rows of lower level table.
For example, upper level table is shops , middle level table is products and lower level table is orders.
Any shop can have many types of products (electronic, furniture etc). Similarly, products can have more than of one type of order (single order, bulk order etc).
Now, with the use of hasManyThrough() function, we can fetch the records of lower level table orders with model of upper level table shops.
Stolen from here: https://demonuts.com/laravel-hasmanythrough/