如何打印商品详情中的属性标题和属性值

问题描述 投票:0回答:1

在我的模型产品中有

public function attributeValues()
{
    return $this->hasMany(AttributesValues::class, 'product_id');
              
}

public function attributes()
{
  return $this->belongsToMany(Attributes::class, 'attribute_product_values', 'product_id', 'attribute_id')
      ->withPivot('attribute_value_id');
      
}

在我的模型属性中有

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

public function typeAttribute()
{
    return $this->belongsTo(TypeAttribute::class, 'type_atributte_id');
}

public function products()
{
    return $this->belongsToMany(Products::class, 'attribute_product_values', 'attribute_id', 'product_id')
        ->withPivot('attribute_value_id');
        
}

在我的模型属性值中

public function productAttribute()
{
    return $this->belongsTo(Attributes::class, 'attribute_id');
}

在我的模型类型属性中

public function attributes()
{
    return $this->hasMany(Attributes::class, 'type_atributte_id');
}

我的控制器产品(展示)

$product = Products::findOrFail($id);
return view('public.product', compact('product'));

在我的产品中。刀片有

@if ($product->attributes->isNotEmpty())
    <h2>Atributos:</h2>
    <ul>
        @foreach ($product->attributes as $attribute)
            {{ $attribute->typeAttribute->id }}
            <li>{{ $attribute->titulo }}:
                 @foreach ($attribute->attributeValues as $value)
                     {{ $value->valor }}
                     @if (!$loop->last), @endif
                 @endforeach
            </li>
        @endforeach
    </ul>
@endif

但它正在打印重复的属性标题。

在一款产品中具有颜色:Rojo、Verde,但打印所有颜色值并重复:

Atributos:
3
Color: Rojo , Verde
3
Color: Rojo , Verde

在其他产品中只有talla-Large和color-Rojo,但打印所有值color、talla和重复:

Atributos:
3
Color: Rojo , Verde
2
Talla: Small , Large
php laravel eloquent eloquent-relationship
1个回答
0
投票

您应该立即加载关系以避免不必要的查询。

$product = Products::query()
    ->with(['attributes.attributeValues'])
    ->findOrFail($id);

$attribute->type_atributte_id
应该与
$attribute->typeAttribute->id
相同,因为它是
BelongsTo
关系。

然后使用

implode()
收集方法应该就够了

@foreach ($product->attributes as $attribute)
  <li>
    <span>{{ $attribute->type_atributte_id }} </span>
    <span>{{ $attribute->titulo }}: </span>
    <span>{{ $attribute->attributeValues->implode('valor', ', ') }}</span>
  </li>
@endforeach
© www.soinside.com 2019 - 2024. All rights reserved.