简体   繁体   中英

Can I use Laravel's eloquent hasManyThrough relationship for my specific case?

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

  • id - integer
  • title - string

Table: post_stacks

  • id - integer
  • post_id - integer
  • stack_id - integer

Table: stacks

  • id - integer
  • body - string
  • url - string

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM