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

concentrico's avatar

HasManyThrough Problem

Hi, I’m trying to do a has many through relationship but I’m having trouble.

I have three tables: orders, articles and items. An item has an order_id and an article_id which are foreign keys (among other fields). On my order model I’m trying to do this:

public function articles()
    {
        return $this->hasManyThrough('App\Article', 'App\Item', 'order_id', 'id');
    }

But the resulting query is:

select `articles`.*, `items`.`order_id`
from `articles`
inner join `items` on `items`.`id` = `articles`.`id` where `items`.`order_id` = 1

Instead of this:

select `articles`.*, `items`.`order_id`
from `articles`
inner join `items` on `items`.`article_id` = `articles`.`id` where `items`.`order_id` = 1

How can I change the inner join condition? From items.id to items.article_id?

0 likes
1 reply
Snapey's avatar
Snapey
Best Answer
Level 122

What you actually have is a straightforward pivot in a many-to-many where the items table is the pivot. You need to tell eloquent the table name (I assume items) because it will default to articles_orders

public function articles()
{
    return $this->belongsToMany('App\Article','items');
}

Please or to participate in this conversation.