【发布时间】:2021-06-15 09:22:12
【问题描述】:
我有两张桌子:
产品:
- 身份证
- 姓名
- category_id
- 说明
分类:
- 身份证
- 姓名
如何显示(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')->find($category_id);之后,您的产品将成为$category->products();下的集合 -
我明白了,我只是不知道该怎么做