产品索引中未显示类别名称

时间:2019-08-16 10:57:53

标签: laravel eloquent laravel-5.8

我要在商品索引页上获取商品,我想显示商品所属的类别的名称,因此仅显示类别ID,但不显示类别名称

刀片文件:

@foreach($products as $product)
<tr>
    <td>
        <a href="{{ route('admin.product.show', $product->id) }}" style="color: #37333d;">
            {{ ucwords($product->product_name) }}
        </a>
    </td>
    <td>{{ $product->product_slug }}</td>
    <td>{{ $product->category_id }}{{ $product->category_name }}</td>
</tr>
@endforeach

产品控制器:

public function index()
{
    $products = Product::all();
    return view('admin.product.index', compact('products'));
}


product.php

      class Product extends Model
      {
      protected $fillable = [
     'product_name', 'product_description', 'product_image', 'category_id', 'product_code', 'product_price', 'product_status', 'product_slug'
    ];

        public function category()
        {
           return $this->belongsTo('App\Category');
        }
      }```

category model:

       class Category extends Model
       {
          protected $fillable = [
         'category_name', 'category_description', 'category_slug', 'category_image'
       ];

         public function products()
         {
            return $this->hasMany('App\Product');
         }
      }

3 个答案:

答案 0 :(得分:1)

1. check your Product.php is their category_name exit or not

2.  where are from category name which model product or category.
  if in category you should get relationship between category and product 


if category name from category model
your code is

public function index()
{
    $products = Product::with('category')->get();
    return view('admin.product.index', compact('products'));
}

make relationship one to one between product & category

答案 1 :(得分:0)

1-在您的产品模型中创建关系

public function category(){
    return $this->belongsTo('App\Category');
}

2-在您的Blade文件中,调用此关系以获取类别的名称:

<td>{{ $product->category_id }}{{ $product->category->name }}</td>

答案 2 :(得分:0)

首先进行控制器更改:

public function index()
{
    $products = Product::with('category')->get();
    return view('admin.product.index', compact('products'));
}

然后您可以执行以下操作:

<td>{{ $product->category_id }}{{ $product->category->category_name }}</td>

如果此解决方案有任何错误,请在此处提供。

祝你好运!