0

i have team and match table. All match information save on match table with two team, winner team, match time etc.

on match table i have three field team_1, team_2, winner_team i want to relation those field with team table

Here is my code

Team Model

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



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

    }

Match Model

class Match extends Model
{
    public function team_1()
    {
        return $this->belongsTo('App\Team','id');
    }

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

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

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

    public function teams() {
        return $this->team_1()->merge($this->team_2());
    }
}

Migration File

Schema::create('matches', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('team_1')->unsigned()->index();
            $table->integer('team_2')->unsigned()->index();
            $table->integer('league_id')->unsigned()->index();
            $table->integer('winner')->nullable();
            $table->dateTime('match_time');
            $table->timestamps();

            $table->foreign('team_1')->references('id')->on('teams')
                ->onDelete('restrict')
                ->onUpdate('cascade');

            $table->foreign('team_2')->references('id')->on('teams')
                ->onDelete('restrict')
                ->onUpdate('cascade');

            $table->foreign('league_id')->references('id')->on('leagues')
                ->onDelete('restrict')
                ->onUpdate('cascade');

            $table->foreign('winner')->references('id')->on('teams')
                ->onDelete('restrict')
                ->onUpdate('cascade');
        });
AH Rasel
  • 161
  • 2
  • 15

1 Answers1

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

public function team_2()
{
    return $this->belongsTo('App\Team', 'team_2');
}
Raúl Monge
  • 223
  • 2
  • 7