Reputation: 119
I'm trying to retrieve data from a table that I don't have a direct relationship with from the model I am currently using.
My data structure:
Table: posts
Table: post_stacks
Table: stacks
My eloquent model is from the Post.php (posts table) and i'm trying to get all the stacks associated to my post (from the stacks table). I want to declare my relationships only on Post.php and not my pivot table (post_stacks). I tried using hasManyThrough but i can't get it to work?
public function img()
{
return $this->hasManyThrough(\App\Stack::class, \App\PostStack::class, 'post_id', 'stack_id', 'id');
}
Would anyone know how i can retrieve my desired data? Thanks!
Upvotes: 1
Views: 459
Reputation: 371
Can you try to put below relationships on your posts model.
public function stacks()
{
return $this->hasManyThrough(
'App\Stacks', 'App\PostStacks',
'post_id', 'id', 'id'
);
}
Also have a look at this, https://laravel.com/docs/5.4/eloquent-relationships#has-many-through
According to this doc, The third argument in hasManyThrough
is the name of the foreign key on the intermediate model. In our case 'post_id'
is the foreign key on post_stack
that has direct relation to posts
.
Fourth argument is the name of the foreign key on the final model. ie, 'id'
on stacks
. that has relationship to post_stacks
( 'post_id' )
. Fifth argument is the local key. ie, id
of posts
Upvotes: 2