基本上,我的数据库中有2个表格:游戏和团队。
每场比赛都必须有2支队伍,所以这是一对多的关系。
我应该在“游戏”表中使用2个外键指向“ Teams”表中的2个球队并具有一对多关系,还是在第三个表中使用“多对多”关系来链接游戏和球队桌子?
我在项目中使用Laravel 6.5,所以我想我在使用Eloquent来实现它。
Schema::create('games', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('team_a_id');
$table->foreign('team_a_id')->references('id')->on('teams')->onDelete('restrict');
$table->unsignedBigInteger('team_b_id');
$table->foreign('team_b_id')->references('id')->on('teams')->onDelete('restrict');
$table->unsignedInteger('team_a_score');
$table->unsignedInteger('team_b_score');
$table->string('status');
$table->boolean('finished');
});
Schema::create('teams', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('abbreviation');
$table->string('country');
$table->timestamps();
});
这是我现在创建的两个表,这是实现它的正确方法吗?
答案 0 :(得分:0)
使用多对多Relationship。在这种情况下,游戏模式可以有多个团队,反之亦然。
因此迁移将是:
Schema::create('games', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('status');
$table->boolean('finished');
});
Schema::create('teams', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('abbreviation');
$table->string('country');
$table->timestamps();
});
Schema::create('game_team', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('game_id');
$table->integer('team_id');
$table->unsignedInteger('score');
$table->timestamps();
});