Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mmstaniewski@gmail.com's avatar

Help with hasManyThrough

Hello, I've a question about hasManyThrough

I've got 3 tables:

Items: id name description

item_categories: item_id category_id

categories: id name description

All i wanna do is to join these 2 tables (items and categories) using item_categories, so ive tried:

public function categories(){
    return $this->hasManyThrough('App\Category', 'App\ItemCategory');
}

What returns: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'categories.item_category_id' in

I dont think it should work like this because Item can has many categories, so why should i assign item id to category table.

I will appreciate every kind of help

0 likes
7 replies
SachinAgarwal's avatar

@Ultearie That is not how you define tables for 'hasManyThrough'. It should be like this:

items: id name description
item_categories: id item_id
categories: id item_categories_id

// And in App/Items
public function categories(){
    return $this->hasManyThrough('App\Category', 'App\ItemCategory');
}

P.S Btw You can achieve this with Many-to-Many relation assuming you have:
An Item have many categories
A Category have many items

mmstaniewski@gmail.com's avatar

I was trying to solve this with many to many, but couldnt get it working, can anybody show me example?

cipsas's avatar

Product Model

public function categories(){
    return $this->hasMany( 'App\Item');
}

Categories Model:

public function items(){
    return $this->hasMany( 'App\Category');
}
1 like
taijuten's avatar

You'd have your two models: Item, Category

Item would belongToMany('App\Category') and vice versa.

You'd then create the category_item table, and this would have two columns. category_id and item_id.

I imagine the reason it wasn't working before, is because the naming convention for pivot tables is in alphabetical order, so your table should be called category_item instead of item_category.

You can override this behaviour by making your relation: belongsToMany('App\Category', 'item_category'), and similarly for the Category model.

1 like
JarekTkaczyk's avatar

@Ultearie

// Item
public function categories()
{
    return $this->belongsToMany(Category::class, 'item_categories');
}

// Category
public function items()
{
    return $this->belongsToMany(Item::class, 'item_categories');
}

@SachinAgarwal You can't do it with hasManyThrough, no matter if you define additional model for the pivot table or not.

SachinAgarwal's avatar

@JarekTkaczyk I even define the table structure for "hasManyThrough" with that table structure it should work.
And I even mentioned He should use "Many to Many" relation. :D

Please or to participate in this conversation.