Laravel-选择关系列

Laravel-选择关系列,laravel,eloquent,Laravel,Eloquent,我试图编写一个查询,从模型中选择列,然后从关系表中选择一列 团队模式 public function members(){ return $this->hasManyThrough('App\User', 'App\Membership', 'team_id', 'id', 'id', 'user_id'); } public function skills() { return $this->belongsToMany('App\Skill'); } 会员(

我试图编写一个查询,从模型中选择列,然后从关系表中选择一列

团队模式

   public function members(){
    return $this->hasManyThrough('App\User', 'App\Membership', 'team_id', 'id', 'id', 'user_id');
}
public function skills()
{
   return $this->belongsToMany('App\Skill');
}
会员(用户)模型

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

我尝试过但没有成功的查询:

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

当我转储查询时,它只返回团队表中
id
name
列的数据,但当我希望它从该表返回名称时,skills关系返回为空

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

如何在此查询中从
skills
关系表中获取
name
列?

您需要将
id
添加到
skills
表返回的字段中。否则,雄辩者无法将技能与正确的团队联系起来

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

要选择相关列,可以使用以下命令:

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

如果您没有在with中传递id属性,则关系无法工作

我刚刚尝试了您的答案,并得到了
完整性约束冲突:字段列表中的1052列“id”不明确
@Lowtiercoder我刚刚更改了答案,请在模型[App\User]上查看未定义的关系[members].我的团队模型包含
成员
有许多粗略的关系,但用户模型没有名为
成员
的关系如果我错了请更正,$这是用于什么模型?用户模型?如果是这样的话,您可以尝试->使用('team.members.skills:id,name')。我不确定团队关系名称,因为您没有显示您的用户模型。我只是尝试了您的答案,得到了答案<代码>完整性约束冲突:字段列表中的1052列“id”不明确请尝试改用
skills.id
。它现在不会出错,但只要我在with语句上方添加select for the team列,技能关系就会返回空。您还需要选择
teams.id
列以匹配记录。