Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
153 views
in Technique[技术] by (71.8m points)

php - How to display related products through pivot table?

I want to display related item which is in same category.

Here is my 3 table structure

food item table : "food_item_id",

"name" ,

"image" ,

food item category table :

"food_item_category_id"

"name"

pivot table

id,

food_item_id

food_item_category_id

FooItem model:

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();
}

Food Category Model:

 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();
}

I want to get all food items from a specific category. Suppose a user clicks on a food item which Id is 1 and It is belongs to category ID 2. Now I want to show more food items which is in the category ID 2. I want to display that in my view blade. Now, how can I display the related products in view which is in the same category?

question from:https://stackoverflow.com/questions/65888617/how-to-display-related-products-through-pivot-table

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As your relation is many to many, you can do this:

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

then you can pass $items to your blade template.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...