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

Cisaia's avatar

hasManyThrough relationship with data from intermediate table

Hello! I am having a problem a with hasManyThrough relationship. I got it to work relatively easily, but now I would like the final product, the collection of items assigned to a product, to include the id and order fields of my intermediate table.

I have three tables

  • products

    • id
  • product_item_rel

    • id
    • product_id
    • item_id
    • order
  • product_items

    • id
    • a bunch of other information

I have created a hasManyThrough relationship on my products model

public function items()
{
    return $this->hasManyThrough(
        'App\Models\ProductItemModels\product_items',               // name of the final model
        'App\Models\ProductItemModels\product_item_rel',            // name of the intermediate model
        'product_id',                                                  // foreign key on the intermediate mode
        'id',                                                       // foreign key on the final model
        'id',                                                       // local key
        'item_id'                                                // local key of the intermediate model
    );
}

This all works great, and using $product->items, I can get all assigned items to my product

The problem I am running into, is that I want two fields from my intermediate table (id, order) to be included in the final collection. Is there a way to rewrite the hasManyThrough relationship to include these two fields from the INTERMEDIATE table?

The reason I need this is

  1. I would like to be able to delete the connection between product and product_item by referencing the connecting product_item_rel id
  2. I would like to be able to order the items based off the "order" field on the product_item_rel
0 likes
3 replies
MarianoMoreyra's avatar
Level 25

Hi @cisaia

Actually, what you have there it's a Many to Many relationship (unless I'm missing something), so maybe it should be easy to define it as that:

ref: https://laravel.com/docs/7.x/eloquent-relationships#many-to-many

Then, you can access any additional columns in your pivot (or intermediate) table by using the following at your relationship definition:

return $this->belongsToMany('App\Role')->withPivot('column1', 'column2');

in your example would be something similar to:

return $this->belongsToMany('App\Models\ProductItemModels\product_items')->withPivot('order');

Hope this helps! (and that I'm not missing something here)

1 like
Cisaia's avatar

Thank you @marianomoreyra ! That was exactly right. It worked like a charm. Im not quite sure why exactly I assumed I needed a hasManyThrough, but I changed it up to a manyToMany (belongsToMany), and everything is working like it should!

Please or to participate in this conversation.