samedi 4 juillet 2020

Cannot get particular attribute values using relation in Laravel

I have three models category,attribute and attribute values, from below code i'm getting all the attributes and its values of a particular category but i want value of a particular attribute.

For eg. if I have an attribute Color i only want that particular attribute and its values, so i want to write a new controller method to get only those attribute, attribute values whose id i pass as a parameter.

Will same model relation be sufficient for this or i have to create new model. Models:

Categories

id | category_name 

Attributes

id | category_id | attr_name

Attribute Values

id | attribute_id | value 

Category Model:

 public function categoryAttributes()
    {
        return $this->hasMany(Attribute::class, 'category_id');
    }

Attribute Model:

 public function attrValues()
   {
       return $this->hasMany(AttributeValues::class,'attribute_id');
   }

View:

@foreach($category->categoryAttributes as $attr)
  
  @foreach($attr->attrValues as $attr_value)
   $attr_value->value
  @endforeach
@endforeach

Controller:

Category::where('id',$categoryId)->with(['categoryAttributes.attrValues'])->first();


via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire