1

I am trying to write a query which selects columns from a model then selects one column from a relationship table.

Team Model

   public function members(){
    return $this->hasManyThrough('App\User', 'App\Membership', 'team_id', 'id', 'id', 'user_id');
}

Member(user) model

public function skills()
{
   return $this->belongsToMany('App\Skill');
}

Function

Query i have attempted but had no luck:

 $members = $this->team->members()
        ->select('id', 'name')
        ->with(['skills' => function ($query) {
          $query->select('name');
        }])
        ->get();

dump of query

When i dump the query it returns just the data for the id and name columns from the team table but the skills relation returns back empty when i want it to return the name from that table.

#relations: array:1 [▼
    "skills" => Illuminate\Database\Eloquent\Collection {#1657 ▼
      #items: []
    }
  ]

How would do i grab the name column from the skills relation table within this query?

0

2 Answers 2

2

To select column in relation you can use this :

->with('members.skills:id,name')

If you're not passing id attribute inside the with, the relation can't work

Sign up to request clarification or add additional context in comments.

5 Comments

I just attemped your answer and got Integrity constraint violation: 1052 Column 'id' in field list is ambiguous
@Lowtiercoder I just've change my answer, take a look
Call to undefined relationship [members] on model [App\User].
my team model contains the members hasmanythrough relation but the user model doesnt have a relation called members
Correct me if i'm wrong, $this is for what Model ? User Model ? if it's that, can you try ->with('team.members.skills:id,name') . i'm not sure for the team relation name because you didn't show you're user model.
1

You need to add the id to the fields returned from the skills table. Otherwise Eloquent has no way to link the skill to the correct team.

->with(['skills' => function ($query) {
    $query->select('id', 'name');
}])

4 Comments

I just attempted your answer and got. Integrity constraint violation: 1052 Column 'id' in field list is ambiguous
Try using skills.id instead.
it doesn't error out now but the skills relationship returns empty as soon as i add the select for the team columns above the with statement
You need to select the teams.id column as well to match the records.