【问题标题】:How to get results of each team laravel如何获取每个团队的结果 laravel
【发布时间】:2021-03-20 21:07:28
【问题描述】:

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

团队模型:

<?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);
    }

【问题讨论】:

  • 您如何评价胜负?这些数据是存储在匹配表还是其他地方?
  • 比赛与分数有关系(match_id, home_team_score, away_team_score)

标签: arrays laravel sorting multidimensional-array eloquent


【解决方案1】:

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

 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);
}

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

【讨论】:

  • 得到这个错误,smth 错误:SQLSTATE[42S22]: Column not found: 1054 Unknown column 'matches.team_id' in 'where clause' (SQL: select * from matches where matches .team_id in (1))
  • matches 表上的外键是什么,它在 teams 表中引用了哪一列?您已经在 Team 模型上定义了 matches 关系 - 您使用哪些列来连接两者
  • 比赛有(league_Id、home_team_id 和 away_team_id)
  • 那么你是如何将匹配定义为 Team 模型与 hasMany 关系的关系?无论如何,您可以通过联赛访问比赛。查看更新的答案。
  • 谢谢。但是如何显示每支球队的所有比赛呢?您是否有一些资源可以让我了解控制器中的这些条件或类似的东西。谢谢。
猜你喜欢
  • 2016-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-13
  • 2017-08-15
  • 1970-01-01
  • 2012-05-09
  • 1970-01-01
相关资源
最近更新 更多