通过财产获得价值

时间:2019-01-10 18:20:53

标签: laravel laravel-5 eloquent

我试图使用范围创建方法,但我感觉我并没有完全达到我的期望。

我的桌子是:

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

所以我需要的是能够通过属性ID来获取值。

例如,我在“产品模型”中的方法将是

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

      return $query...

    }

然后像这样调用控制器

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

什么是最好的方法?我无法使其正常工作或找到最佳方法,除了使用范围之外,还有其他更好的方法吗?

1 个答案:

答案 0 :(得分:1)

@Levente Otta是正确的,可能您需要使用以下关系:

localhost

然后,您可以在控制器中像这样访问:

// 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');
}

希望您能在这里找到要点。

相关问题