【发布时间】:2020-07-04 16:56:10
【问题描述】:
我有三个模型类别,属性和属性值,从下面的代码中,我得到了特定类别的所有属性及其值,但我想要特定属性的值。
例如。如果我有一个属性 Color 我只想要那个特定的属性及其值,所以我想编写一个新的控制器方法来只获取那些属性,即我作为参数传递的 id 的属性值。
相同的模型关系是否足以满足此要求,或者我必须创建新模型。 型号:
类别
id | category_name
属性
id | category_id | attr_name
属性值
id | attribute_id | value
类别模型:
public function categoryAttributes()
{
return $this->hasMany(Attribute::class, 'category_id');
}
属性模型:
public function attrValues()
{
return $this->hasMany(AttributeValues::class,'attribute_id');
}
查看:
@foreach($category->categoryAttributes as $attr)
{{ $attr->attr_name }}
@foreach($attr->attrValues as $attr_value)
$attr_value->value
@endforeach
@endforeach
控制器:
Category::where('id',$categoryId)->with(['categoryAttributes.attrValues'])->first();
【问题讨论】:
标签: laravel laravel-5 eloquent