We're creating a new product system in the Laravel framework where we've got a problem setting up the relations between the models and pivots correctly. The situation can be displayed as the following:
A product can have certain Attributes like Color for instance. This is saved in the morph_has_attributes
table. However, we would also like to set the value of this 'color' attribute. This could easily be done by having a attribute_value_id
in the morph_has_attributes
table. However, we'd like to be able to bind multiple values to the attribute, which is why there is a many-to-many relation between the pivot and the attribute value.
An example: I sell a Car (product) which has multiple Colors (Attribute): Green and Red (Values).
I've found the following Article which looks like my situation, however, in their case the AttributeValue has the key instead of the MorphHasAttributeValue.
My goal is to set up the relation between the Product (or Search, which is similar because of the Polymorphic relation) and the AttributeValues.
The relations I'm currently using look like this:
The Product Class
class Product extends Model
{
/**
* Get all of the attributeTypes for the product.
*/
public function attributeTypes()
{
return $this->morphToMany('App\AttributeType', 'morph', 'morph_has_attributes');
}
/**
* Get all of the morphHasAttributeValues pivots for the product.
*/
public function morphHasAttributeValues()
{
return $this->hasMany('App\Pivots\MorphHasAttributeValue')
->using('App\Pivots\MorphHasAttribute');
}
/**
* The attributeValues that are bound to this product .
*/
public function attributeValues()
{
// How do I do this?
}
}
The MorphHasAttribute Class
class MorphHasAttribute extends MorphPivot
{
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'morph_has_attributes';
public function products()
{
return $this->belongsTo('App\Product');
}
public function searches()
{
return $this->belongsTo('App\Search');
}
public function productHasAttributeValues()
{
return $this->belongsTo('App\ProductHasAttributeValue');
}
public function attributeValues()
{
return $this->belongsToMany('App\AttributeValue', 'morph_has_attribute_value');
}
}
The MorphHasAttributeValue Class
class MorphHasAttributeValue extends Pivot
{
public function products()
{
return $this->belongsToMany('App\Product')
->using('App\Pivots\MorphHasAttribute');
}
}
The AttributeValue Class
class AttributeValue extends Model
{
//
}