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.
Oct 9, 2015
2
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!
Level 52
1 like
Please or to participate in this conversation.