如何在laravel中建立两个表之间的关系?

问题描述 投票:0回答:2

我的数据库有两个表“游戏”和“团队”。

游戏迁移:

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

这两个表之间有什么关系?多对多? 我应该创建“game_team”数据透视表吗?

我尝试更改数据库的设计,但没有解决问题

laravel database foreign-keys relationship
2个回答
0
投票

你描述的是两种1:n的关系。 一场比赛有一支主队和一支客队。 您不需要额外的桌子。

您应该使用带有 _id 后缀的名称作为外键,因为 laravel 模型喜欢这样。

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

在你的游戏模型中你可以说

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

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

像这样使用它

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

这就是laravel的魔力(雄辩)。

干杯


-1
投票

为了更准确地设计数据库,需要更多细节,但无论如何,根据你的解释,比赛和球队表之间的关系一定是

one-to-many

实际上你需要两个一对多的关系。每场比赛都有两个外键,一个用于主队,另一个用于客队,它们都引用

id
表中的
teams
列。每场比赛属于一支主队和一支客队,并且每支球队可以有多场与之相关的比赛。

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');
});
© www.soinside.com 2019 - 2024. All rights reserved.