Pedro
Pedro

Reputation: 1477

Get value by property

im trying to create a method using scope bu i feel that im not quite getting what i expect.

My Tables are:

Products:
 - id;
 - name
...

properties:
- id;
- name
- identifier
- data_type
- field_type

products_properties
- product_id
- property_id

product_property_integer_values | product_property_text_values | product_property_datetime_values | product_property_varchar_values
 - product_properties_id;
- value (depending of the data data_type of properties, this could be integer, text, boolean or datetime

So what i need is to be able to get the value by the property id.

For example my method in the Product Model would be.

public function scopeGetPropertyValue($query, $attribute)
    {
     $property = Property::where('identifier',$attribute)->first();

      return $query...

    }

Then calling in controller like:

$product = Product::where('slug',$slug)->firstOrFail();
$brand = $product->getPropertyValue('brand');

What would be the best way? I cant get it work or find the best way in doing, is there a better way beside using scope?

Upvotes: 0

Views: 705

Answers (1)

Mike Harrison
Mike Harrison

Reputation: 1393

@Levente Otta is correct, it is probably something that you need to use relations for:

// App\Product
public function properties()
{
    return $this->hasManyThrough(Property::class, ProductProperty::class);
}

public function brands() //this is for the brand property
{
    return $this->properties()
                ->where('identifier', 'brand');
}

Then in your controller you can access like this:

$product = Product::where('slug', $slug)->firstOrFail();
$brand = $product->brands()->first(); //get the first brand
$brands = $product->brands; //get all brands for the product
$my_other_property = $product->properties()->where('identifier', 'my_other_property')->first(); //get first prop called 'my_other_property'

Hopefully you get the gist here.

Upvotes: 1

Related Questions