Ruchita Sheth
Ruchita Sheth

Reputation: 860

Eloquent hasManyThrough also get middle table information

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..

Upvotes: 1

Views: 2110

Answers (2)

Jesus Erwin Suarez
Jesus Erwin Suarez

Reputation: 1585

Try this one:

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

Upvotes: 1

D. Petrov
D. Petrov

Reputation: 1167

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.

Upvotes: 4

Related Questions