首页 > 解决方案 > 如何获取每个团队的结果 laravel

问题描述

我需要为每个联赛创造积分榜。关系:

团队模型:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Team extends Model
{
    protected $fillable = ['name', 'league_id', 'stadium'];

    public function league() {
        return $this->belongsTo('App\League');
    }

    public function players() {
        return $this->hasMany('App\Player');
    }

    public function matches() {
        return $this->hasMany('App\Match');
    }
    
}

匹配型号:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use App\Team;

class Match extends Model
{
    protected $fillable = ['round', 'match_date'];
    protected $guarded = ['league_id', 'home_team_id', 'away_team_id'];  

    public function leagues() {
        return $this->belongsTo('App\League');
    }

    public function homeTeam() {
        return $this->belongsTo('App\Team', 'home_team_id');
    }

    public function awayTeam() {
        return $this->belongsTo('App\Team', 'away_team_id');
    }

    public function score()
    {
        return $this->hasOne('App\Score', 'match_id');
    }
}

创建积分榜功能,当获取联赛的所有球队。排名应该有比赛,胜利,平局,失败。有人可以帮忙,如何获取这些数据?

 public function standings(League $league, Team $team) {
        $teams = Team::with('league')->where('league_id', $league->id)->get();
       
        //dd($team_matches);
        return view('admin.leagues.standings')->with('teams',$teams);
    }

标签: arrayslaravelsortingmultidimensional-arrayeloquent

解决方案


获取所有数据的一种方法是

 public function standings(League $league, Team $team) {
    $teams = Team::where('league_id', $league->id)
        ->with([
            'league.matches.score' 
        ])
        ->get();
       
    //dd($team_matches);
    return view('admin.leagues.standings')->with('teams',$teams);
}

然后在视图中渲染时,您可以根据分数计算输赢。


推荐阅读