laravel 为什么我不能将 releationshiop 用于通过连接获取的数据

laravel why i cant use releationshiop for data get with join

这是我的控制器:

 $homeTeamFacts = DB::table('match_facts')
            ->where('match_id', $match->id)
            ->join('players', 'match_facts.player_id', '=', 'players.id')
            ->where('players.team_id', '=', $homeTeamId)
            ->get();

这是我收集的数据:

Illuminate\Support\Collection {#1311 ▼
  #items: array:4 [▼
    0 => {#1325 ▼
      +"id": 2
      +"match_id": "1"
      +"player_id": "2"
      +"minutes": 90
      +"goals": null
      +"yellowCard": 1
      +"redCard": 0
      +"bench": 0
      +"created_at": "2021-01-08 11:12:59"
      +"updated_at": "2021-01-08 11:12:59"
      +"team_id": "1"
      +"position": "Gynėjas"
      +"photo": null
      +"name": "Tomas"
      +"surname": "Tomaitis"
      +"birth_date": null
      +"city": null
      +"height": null
      +"weight": null
    }
    1 => {#1332 ▶}
    2 => {#1323 ▶}
    3 => {#1333 ▶}
  ]
}

问题是当我试图用“{{$fact -> player-> name}}”让玩家名字出现在视图中时 当我收到这样的错误时“Undefined 属性: stdClass::$player (View:..... "

但是当我得到这样的数据时:

$MatchFacts = Match_fact::where('match_id', $match->id)
        ->get();

没有问题,关系很好。 是否有任何选项可以使关系解决我提到的问题?

我认为当你加入多个 table 意味着结果将不是该模型的实际实例将只是一个数据集合,这就是关系不起作用的原因,你可以得到名称通过添加 select 来指定播放器的列 您是否可以将播放器的名称添加为列 selected 所以在数据集合中将是播放器的名称player_name

 $homeTeamFacts = DB::table('match_facts')->select([                DB::raw('players.name as player_name'),])

        ->where('match_id', $match->id)
        ->join('players', 'match_facts.player_id', '=', 'players.id')
        ->where('players.team_id', '=', $homeTeamId)
        ->get();

这是因为您是直接通过查询生成器进行查询,而不是使用 Eloquent。这样,结果就不会被水化为 Match_fact 个实例,而是常见的 stdClass 实例。因此,没有在这些上定义 player 关系。

要解决此问题,请尝试使用 Eloquent 和关系查询您的数据

$MatchFacts = Match_fact::with('player')
        ->where('match_id', $match->id)
        ->get();

如果您在 Match_fact 上正确定义了 player 关系,那么您应该可以这样做:

@foreach($MatchFacts as $fact)
  {{ $fact->player->name }}
@endforeach

在您的情况下,您正在使用查询生成器从数据库中检索数据 DB::table('match_facts')

您可以使用查询生成器获取玩家姓名,只需将 select players.name 添加到您的 select() 方法

$homeTeamFacts = DB::table('match_facts')
    ->where('match_id', $match->id)
    ->join('players', 'match_facts.player_id', '=', 'players.id')
    ->where('players.team_id', '=', $homeTeamId)
    ->select('match_facts.*', 'players.name  as player_name')
    ->get();

现在您可以使用 $fact->player_name

访问玩家名称

但我认为使用模型和关系是更好的选择