Search code examples
laraveldatabaseforeign-keysrelationship

How to make relationship between two tables in laravel?


my database has two tables "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 the design of the database but it didn't fix it


Solution

  • 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 = \App\Models\Game::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