Shaheryar TVS
Shaheryar TVS

Reputation: 45

Laravel Eloquent: Product, Attributes and Attribute Values Relationship

I've a scenario for product and attributes relationship.

Models:

  1. Product (table: products)
  2. Attributes (table: attributes)
  3. Attribute Values (table: attribute_values, foreign key: attribute_id)

A product can have multiple attributes so this will be easy with many to many relation b/w product and attributes

Model: Attribute

<?php

class Attribute extends Model{
    public function products()
    {
       return $this->belongsToMany(Product::class);
    }
}

Model: Product

class Product extends Model{
    public function attributes()
    {
       return $this->belongsToMany(Attribute::class);
    }
}

but, when assigning an attribute to an item user can opt out one of the attribute value from attribute_values i.e., the values assigned to an attribute.

how can I manage this in eloquent way?

Upvotes: 1

Views: 3349

Answers (2)

Faisal
Faisal

Reputation: 162

enter image description here I have designed a database schema, is that true ?

Upvotes: 1

Rocco Milluzzo
Rocco Milluzzo

Reputation: 1007

In this case I would create a Pivot between products and attribute_values, and than you can use it the "Eloquent way" like this:

$products->sync(AttributeValues::where('attribute_id',$attribute_id);

and then if you want to detach a single attribute_value you can detach it using its instance

Upvotes: 0

Related Questions