【问题标题】:Cannot get particular attribute values using relation in Laravel无法使用 Laravel 中的关系获取特定属性值
【发布时间】: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


    【解决方案1】:

    您只是忘记添加 {{ }}

    {{ $attr_value->value }}


    编辑

    既然你想要的只是一个带有它的值的属性,那就创建一个新方法。

    public function fetchAttribute(Request $request)
    {
        $attribute = Attribute::with('attrValues')->find($request->get('attr_id'));
    
        return response()->json($attribute);
    }
    

    【讨论】:

    • 谢谢,但我想获取特定属性及其值,我将如何在控制器和视图中编写它,但是从上面的代码中,我得到了所有属性和属性值。
    • 请求中是否传递了属性id?
    • :是的,属性 id 将通过 ajax 函数传递给控制器​​,我必须在模式中显示该特定属性及其属性值
    • 更新了我的答案。请看一看。
    猜你喜欢
    • 2023-04-06
    • 2018-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-09
    • 2020-02-08
    • 2016-09-12
    • 1970-01-01
    相关资源
    最近更新 更多