In Laravel 5.5 I try to create a small application to manage products of a couple of sellers/stores.
Therefore, I have four different models like this:
Seller.php
class Attribute extends Model
{
public function items()
{
return $this->belongsToMany(Item::class);
}
}
Item.php
class Item extends Model
{
public function seller()
{
return $this->belongsTo(Seller::class);
}
public function category()
{
return $this->belongsTo(Category::class);
}
public function attributes()
{
return $this->belongsToMany(Item::class);
}
}
Category.php
class Category extends Model
{
public function items()
{
return $this->hasMany(Item::class);
}
}
Attribute.php
class Attribute extends Model
{
public function items()
{
return $this->belongsToMany(Item::class);
}
}
For the many-to-many relation between Attributes & Items, I created a pivot table:
Schema::create('attribute_item', function (Blueprint $table) {
$table->integer('attribute_id')->unsigned()->index();
$table->foreign('attribute_id')->references('id')->on('attributes')->onDelete('cascade');
$table->integer('item_id')->unsigned()->index();
$table->foreign('item_id')->references('id')->on('items')->onDelete('cascade');
$table->primary(['attribute_id', 'item_id']);
});
The goal of the entire application is to:
- fetch all items of a seller by category with attributes (for filtering or something)
- Fetch a specific item of an seller and get its attributes and category
I'm a little bit confused by Laravels relationhip methods and which one to use in that case.
May it is better to hasManyThrough
or polymorphic relationhips?
I have to admit that I have a little logic problem here. Hopefully you can help me.
Thank you!