如何通过pivot table显示相关产品?

How to display related products through pivot table?

我想显示同一类别的相关项目。

这是我的 3 table 结构

食品table : "food_item_id",

"姓名",

"图片",

食品类别table:

"food_item_category_id"

“姓名”

枢轴table

id,

food_item_id

food_item_category_id

FooItem 型号:

public function foodItemCategory() {
    return $this->belongsToMany(FoodItemCategory::class, 'food_items_have_categories', 'food_item_id', 'food_item_category_id')
        ->withPivot('food_item_id', 'food_item_category_id')
        ->withTimestamps();
}

食品分类型号:

 public function foodItem() {
    return $this->belongsToMany(FoodItem::class, 'food_items_have_categories', 'food_item_category_id', 'food_item_id')
        ->withPivot('food_item_id', 'food_item_category_id')
        ->withTimestamps();
}

我想获取特定类别的所有食品。假设用户单击 ID 为 1 且属于类别 ID 2 的食品。现在我想显示类别 ID 2 中的更多食品。我想在我的视图中显示它 blade . 现在,如何在同一类别的视图中显示相关产品?

由于你的关系是多对多的,你可以这样做:

$food = FoodItem::find(1);
$categories = $food->foodItemCategory;
$items = [];
foreach($categories as $category) {
   $items[$category->id] = $category->foodItem;
}

然后您可以将 $items 传递给您的 blade 模板。