EDGE
EDGE

Reputation: 53

How to get relations using pivot table in Laravel

I have 4 tables similar to this:

items (id)

subcategories (id | category_id)

item_subcategory (item_id | subcategory_id) --pivot table

categories (id)


The items and subcategories are connected to the pivot table with many to many relationship. How can I get all the items under each categories? Below is an example.

Upvotes: 0

Views: 1247

Answers (2)

Mudit Gulgulia
Mudit Gulgulia

Reputation: 1266

There can be 3 ways we could use from my perspective, I'll share all.

  1. Linking Relations: You can link relations on top of other relations eg.
Category::with(['subcategories' => function ($query) {
   $query->whereHas('items');
}])->get();

It will get all the subcategories first, then the related items something like that =>

[{
    "id": 1,
    "title": "Category 1",
    "subcategories": [{
        "id": 1,
        "category_id": 1,
        "title": "Subcategory 1",
        "items": [{
            "id": 1,
            "title": "Item 1",
            "pivot": {
                "subcategory_id": 1,
                "item_id": 1
            }
        }]
    }]
}]
  1. Add category id into a pivot table and make new relation eg:
public function items()
{
   return $this->belongsToMany(Item::class, ItemSubcategory::class);
}

It will allow you to directly fetch products without loading subcategories first, something like that.

[{
    "id": 1,
    "title": "Category 1",
    "items": [{
        "id": 1,
        "title": "Item 1",
        "pivot": {
            "category_id": 1,
            "item_id": 1
        }
    }]
}]
  1. Using hasManyThrough, you can create a relation by depending on other classes if your item table contains a subcategory id.
    public function items()
    {
        return $this->hasManyThrough(Item::class, ItemSubcategory::class, null, 'id', null, 'item_id');
    }

Upvotes: 2

Atakan ATICI
Atakan ATICI

Reputation: 11

I don't understand completely but maybe this will be a solution for you, in your model

public function Categories()
    {
        return $this->hasMany(Category::class,'id', 'categoryID');
    }

Upvotes: 0

Related Questions