首页 > 解决方案 > 带有枢轴的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

我认为这是因为我在循环中有一个循环。我怎样才能调整它只返回一次状态。

标签: phplaravel

解决方案


我能够通过创建另一个查询并将其添加为刀片衍生产品来解决此问题。

刀片衍生产品

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

推荐阅读