1

I have same table structure as mentioned in laravel document for HasManyThrough relationship hasManyThrough

countries
  id - integer
  name - string 

users
  id - integer
  country_id - integer
  name - string

posts
  id - integer
  user_id - integer
  title - string

and define a relationship like same as in doc.

public function posts()
{
    return $this->hasManyThrough(
        'App\Post', 'App\User',
        'country_id', 'user_id', 'id'
    );
}

Now when I List posts of specific country. I need the information of user of the post too. I mean information from pivot table(users)

$posts = Country::find(2)->posts();

The above returns post data only..

Ruchita Sheth
  • 840
  • 9
  • 27

2 Answers2

4

What you need is to eager load the users alongside the posts, can be achieved via the with() method on the Builder:

$posts = Country::find(2)->posts()->with('user')->get();

If you're loading huge amounts of data and don't want the whole User instance loaded, you can even specify which fields to only be retrieved from the users table:

$posts = Country::find(2)->posts()->with('user:id,name')->get();

Then you can simply use $post->user->name or whatever you need when iterating your collection.

Refer to the documentation for more information.

D. Petrov
  • 1,147
  • 15
  • 27
  • for eager loading first I need to define relationship between post and user right...? Or It will work with my currention defined hasManyThrough relationship? – Ruchita Sheth May 17 '19 at 07:13
  • 1
    You'll have to define the relationship in the `Post` model, but I'd say it's worth the effort. You may need the relationship later on as well, it's not going to be obsolete since it exists anyway. :) – D. Petrov May 17 '19 at 07:15
  • Thanks... Its working.. I was just stick with hasManyThrough relationship to find a way out. and haven't think about other relationship to take in picture.. – Ruchita Sheth May 17 '19 at 07:27
  • one more help needed. this gives me error. Country::find(2)->posts()->with('user:id,name')->get(); insted of id my column name is id_user – Ruchita Sheth May 17 '19 at 07:37
  • Well that was only an example, of course you must change `id` with `user_id` if that matches your column's name. – D. Petrov May 17 '19 at 07:38
1

Try this one:

$posts = Country::find(2)->posts()->with('user')->get();
Jesus Erwin Suarez
  • 1,571
  • 16
  • 17