从 collection 中检索关系项
Retrieve relationship items from a collection
在控制器中,我创建了一个 collection:
$playershome = App\Team::where('id', $session->team1_id)->with('players')->first();
并调用我的视图:
return view('member.home', compact('user', 'session', 'playershome', 'playersaway'));
在我的团队模型中,我:
public function players(){
return $this->belongsToMany(User::class, 'team_users');
}
创建了collection:
但我不知道如何在我的视图中检索 "players" 项。
我尝试:
@foreach($playershome->players as $player)
但是我得到了:
Invalid argument supplied for foreach()
怎么了?
更新视图:
<div class="mt-body">
<h3 class="mt-body-title"> {{$session->team1Id->name}} </h3>
<p class="mt-body-description"> It is a long established fact that a reader will be distracted </p>
<ul class="mt-body-stats">
@foreach($playershome->players as $player)
<li class="font-green">
<img src="/storage/{{$player->avatar}}"></li>
@endforeach
</ul>
<div class="mt-body-actions">
<div class="btn-group btn-group btn-group-justified">
<a href="javascript:;" class="btn">
<i class="icon-bubbles"></i> Punti </a>
<a href="javascript:;" class="btn ">
<i class="icon-social-twitter"></i> K/D </a>
</div>
</div>
</div>
这样试试
$playershome = App\Team::with('players')->where('id', $session->team1_id)->get();
查看您在评论中的聊天记录,我发现您在团队 table 中对名为 players
的属性使用相同的名称,并且与用户的关系也是称为 players
。尝试重命名与其他内容的关系,在您的查询和 foreach 中更改它。
编辑:找到与您相同问题的 Whosebug 问题:
在控制器中,我创建了一个 collection:
$playershome = App\Team::where('id', $session->team1_id)->with('players')->first();
并调用我的视图:
return view('member.home', compact('user', 'session', 'playershome', 'playersaway'));
在我的团队模型中,我:
public function players(){
return $this->belongsToMany(User::class, 'team_users');
}
创建了collection:
但我不知道如何在我的视图中检索 "players" 项。 我尝试:
@foreach($playershome->players as $player)
但是我得到了:
Invalid argument supplied for foreach()
怎么了?
更新视图:
<div class="mt-body">
<h3 class="mt-body-title"> {{$session->team1Id->name}} </h3>
<p class="mt-body-description"> It is a long established fact that a reader will be distracted </p>
<ul class="mt-body-stats">
@foreach($playershome->players as $player)
<li class="font-green">
<img src="/storage/{{$player->avatar}}"></li>
@endforeach
</ul>
<div class="mt-body-actions">
<div class="btn-group btn-group btn-group-justified">
<a href="javascript:;" class="btn">
<i class="icon-bubbles"></i> Punti </a>
<a href="javascript:;" class="btn ">
<i class="icon-social-twitter"></i> K/D </a>
</div>
</div>
</div>
这样试试
$playershome = App\Team::with('players')->where('id', $session->team1_id)->get();
查看您在评论中的聊天记录,我发现您在团队 table 中对名为 players
的属性使用相同的名称,并且与用户的关系也是称为 players
。尝试重命名与其他内容的关系,在您的查询和 foreach 中更改它。
编辑:找到与您相同问题的 Whosebug 问题: