skip to Main Content

my database has two table games and teams,
games migration:

$table->unsignedBigInteger('homeTeam');
$table->unsignedBigInteger('awayTeam');
$table->foreign('homeTeam')->references('id')->on('teams')
$table->foreign('awayTeam')->references('id')->on('teams')

what is relationship between this two table? many to many? should I create "game_team" pivot table?

i tried to change design of database but it don’t fixed

2

Answers


  1. More details are needed for a more accurate design of the database, but anyway, according to your explanation, the relationship between the games and teams table must be one-to-many .

    actually you need two one-to-many relation . Each game has two foreign keys, one for the home team and another for the away team, which both reference the id column in the teams table. that each game belongs to one home team and one away team, and each team can have multiple games associated with it.

    Schema::create('teams', function (Blueprint $table) {
        $table->id();
        // Other teams columns
    });
    
    
    Schema::create('games', function (Blueprint $table) {
        $table->id();
        // Other game columns
        $table->unsignedBigInteger('home_team');
        $table->unsignedBigInteger('away_team');
        $table->foreign('home_team')->references('id')->on('teams');
        $table->foreign('away_team')->references('id')->on('teams');
    });
    
    Login or Signup to reply.
  2. what you describe is two 1:n relationships.
    A game has one home team and one away team.
    You don’t need an additional table.

    You should use names with _id suffix for foreign keys because laravel models like it that way.

    Schema::create('games', function (Blueprint $table) {
        $table->id();
        // Other game columns
        $table->foreignId('home_team_id');
        $table->foreignId('away_team_id');
    
        $table->foreign('home_team_id')->references('id')->on('teams');
        $table->foreign('away_team_id')->references('id')->on('teams');
    });
    

    In your Game model you can then say

    public function home_team(): BelongsTo
    {
        $this->belongsTo(Team::class, 'home_team_id');
    }
    
    public function away_team(): BelongsTo
    {
        $this->belongsTo(Team::class, 'away_team_id');
    }
    

    to use it like

    $game = AppModelsGame::first();
    $team1 = $game->home_team;  // get the home team
    $team2 = $game->away_team;  // get the away team
    

    That is the magic of laravel (eloquent).

    Cheers

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search