BrendanDodd
BrendanDodd

Reputation: 297

Laravel - hasManyThrough and eager loading, get column from related

I'm getting some weird stuff going on when trying to eager load a related model using hasManyThrough.

I have a Community model which has a function called 'roommates' to get all Users that have the community id in a column called 'community', see below code.

    public function roommates()
    {
        return $this->hasManyThrough('App\User', 'App\Community', 'id', 'community');
    }

Then the User model is grabbed from Auth after login and eager loads the related models, and only displaying the columns I want. id, name, email

$user = User::where('id', Auth::id())->with(['community.roommates' => function ($query) 
        {
            $query->select('users.id', 'name', 'email');
        }])->first();

However my JSON response isn't what I expected, the id that is being returned appears to be the id of the community, even though I have specified 'users.id'

{
"status": true,
"data": {
"id": 3,
"name": "Foo Bar",
"email": "[email protected]",
"community": {
  "id": 1,
  "owner": 3,
  "title": "Home",
  "created_at": "2015-10-09 08:04:05",
  "updated_at": "2015-10-09 08:04:05",
  "roommates": [
    {
      "id": 1,
      "name": "Foo Bar 2",
      "email": "[email protected]"
    },
    {
      "id": 1,
      "name": "Foo Bar",
      "email": "[email protected]"
    }
  ]
},
"remember_token": "tprkiNOYbBiViwQkVcJMcwU8poZ1/00Uktmy7AQ+",
"created_at": "2015-10-09 08:03:42",
"updated_at": "2015-10-10 04:56:14"
}
}

As you can see the id on both users in the roommates array is 1, however the ids of those users are 2 and 3.

Any ideas?

I'm still feeling around with Laravel so I'm not sure where to go from here?

Upvotes: 1

Views: 2187

Answers (1)

BrendanDodd
BrendanDodd

Reputation: 297

Ending up working it out,

I changed to use hasMany instead of hasManyThrough

    public function roommates()
    {
        return $this->hasMany('App\User', 'community_id', 'id')->select(['community_id', 'id', 'name', 'email']);
    }

And also I needed to select the foreign key, community_id, or else I would get a blank result.

Credits to this question helping me figure it out

Laravel Eager Loading - Load only specific columns

Upvotes: 1

Related Questions