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

uxweb's avatar
Level 20

How to create this hasManyThrough relationship?

Hi everybody, i'm having trouble with an eloquent relationship i want to do:

Currently, i have these 3 tables:

Locations
id
name

Stocks
id
location_id
product_id
on_hand

Products
id
name
// Location.php

public function products()
    {
        return $this->hasManyThrough(Product::class, Stock::class);
    }

Tried to create a hasManyThrough relationship on Location through Products, to get "the products in stock for a location", but it is not working because the query is taking the primary key of the intermediate model (Stock) to join with the primary key of the related model (Product).

select
    [products].*, 
    [stocks].[location_id]
from
    [products] 
inner join
    [stocks]
on
    [stocks].[id] = [products].[id]  // <---- here is the problem
// it should be [stocks].[product_id] = [products].[id]
where
    [stocks].[location_id] in (26)

Is there a way to achieve this with eloquent?, also, is it possible to add the "on_hand" field from every product stock?

Thanks!

0 likes
2 replies
bestmomo's avatar
Level 52

The hasManyThrough is if you have 2 hasMany with 3 tables, it's not your case. You have a many to many relation so you must use a belongsToMany method.

1 like

Please or to participate in this conversation.