【问题标题】:How can I display (foreach) all products in a certain category?如何显示(foreach)某个类别中的所有产品?
【发布时间】:2021-06-15 09:22:12
【问题描述】:

我有两张桌子:

产品:

  1. 身份证
  2. 姓名
  3. category_id
  4. 说明

分类:

  1. 身份证
  2. 姓名

如何显示(foreach)某个类别的所有产品?

产品型号:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $fillable = ['name', 'category_id', 'description',];

    public function category()
    {
        return $this->belongsTo(Category::class);
    }

}

类别模型:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    protected $fillable = ['name',];

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

}

类别控制器:

public function show($id)
    {
        //
        $categories = Product::where('category_id', '=', $id)->get();
        
        return view ('categories.show',compact('categories'));
    }

Show.blade.php:

@foreach ($categories as $product)
             
{{$product->category_id}}
            
@endforeach

{{ $product->category->name }}

【问题讨论】:

  • 使用模型中显示的 eloquent 关系,您只需要将您的类别加载为$category = Category::with('products')-&gt;find($category_id); 之后,您的产品将成为$category-&gt;products(); 下的集合
  • 我明白了,我只是不知道该怎么做

标签: php laravel


【解决方案1】:

你在 categoryController 中,你得到一个对象——一个由 id 而不是集合的类别。所以刀片文件中不会有类别。你在这里做的是收集产品。您应该通过这样做来反转您的查询

public function show($id)
{
    $category = Category::with(['products'])->find($id);
    
    return view ('categories.show', compact('category'));
}

在刀片文件中

@foreach ($category->products as $product)
    {{$product->name}}
@endforeach

{{ $category->name }}

【讨论】:

    【解决方案2】:

    据我了解,在控制器中,添加这个,

    $categories = Product::with('category')-&gt;where('category_id', '=', $id)-&gt;get();

    然后在您的刀片中,您可以在 foreachloop 中以$categories-&gt;category-&gt;name

    的形式访问$categories

    【讨论】:

      【解决方案3】:

      在您的 Show.blade.php 文件中添加以下代码:

      @if($categories)
          @foreach($categories AS $category)
               <div class="">
                   {{ $category->category_id.': '.$category->name }}
               </div>
               @if($category->products)
                   @foreach($category->products AS $product)
                       <div classs="">
                           {{ $product->id.': '.$product->name }}
                       </div>
                       <div classs="">
                           {{ $product->Description }}
                       </div>
                   @endforeach
               @endif
          @endforeach
      @endif
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多