php - 带有枢轴的Larvel foreach
问题描述
我与枢轴有多对多关系
锦标赛模型
public function teams()
{
return $this->belongsToMany('App\Models\APP\Team\Team', 'team_tourney')->withPivot('status')->withTimestamps();
}
团队模型
public function tourneys()
{
return $this->belongsToMany('App\Models\APP\Tourney\Tourney', 'team_tourney')->withPivot('status')->withTimestamps();
}
用户模型
public function tourneys()
{
return $this->hasMany('App\Models\APP\Tourney\Tourney');
}
public function teams()
{
return $this->hasMany('App\Models\APP\Team\Team');
}
控制器显示功能:
$tourney = Tourney::with('user', 'teams')->where('slug', $slug)->first();
$teams = Team::with('tourneys')->where('user_id', auth()->user()->id)->get();
在我看来,我需要首先获取用户团队的列表。然后检查锦标赛团队是否包含任何用户团队并列出它们。
@foreach($teams as $team)
{{-- List teams if already attached --}}
@if($tourney->teams->contains($team))
{{-- Get TourneyTeam status --}}
@foreach($tourney->teams as $tourneyTeam)
<p>{{$tourneyTeam->pivot->status}}</p>
@endforeach
@endif
@endforeach
这样做时,我会打印两次状态。例如,返回 11 而不是 1
我认为这是因为我在循环中有一个循环。我怎样才能调整它只返回一次状态。
解决方案
我能够通过创建另一个查询并将其添加为刀片衍生产品来解决此问题。
刀片衍生产品
Blade::if('teamTourneyStatus', function($tourney, $team){
$team = $tourney->teams->where('id', $team->id)->first();
if($team->pivot->status == 1){
return true;
}
return false;
});
更新视图
@foreach($teams as $team)
{{-- List teams if already attached --}}
@if($tourney->teams->contains($team))
{{-- Get TourneyTeam status --}}
@teamTourneyStatus($tourney, $team) "show if true" @endteamTourneyStatus
@endif
@endforeach
推荐阅读
- git - 如何摆脱 Visual Studio 2019 中的密码提示?
- html - 图像在
- javascript - Next.js getStaticProps 将数据作为对象传递
- linux - Fedora 35 上的 httpd localhost 服务器出现错误 503
- python - LSTM 一对多用例
- networking - 网络的度数分布
- python-3.x - 循环遍历 Python 中的列表列表
- c - gdb 内存地址与程序打印出的内存地址不匹配
- python - python有嵌套类依赖吗?
- javascript - 无法从 Javascript 中的 REST-API 访问 JSON 响应的变量