Php 在二对多关系上使用两个表,或在数据透视表上使用三个表
基本上,我的数据库中有两个表:游戏和团队 每场比赛必须有两支球队,所以这是一种二对多的关系 我应该在我的游戏表中使用2个外键指向团队表中的2个团队,并具有一对多关系,还是使用与第三个表的多对多关系来链接游戏和团队表 我在项目中使用Laravel6.5,所以我想我在使用Elount来实现它Php 在二对多关系上使用两个表,或在数据透视表上使用三个表,php,mysql,database,laravel,eloquent,Php,Mysql,Database,Laravel,Eloquent,基本上,我的数据库中有两个表:游戏和团队 每场比赛必须有两支球队,所以这是一种二对多的关系 我应该在我的游戏表中使用2个外键指向团队表中的2个团队,并具有一对多关系,还是使用与第三个表的多对多关系来链接游戏和团队表 我在项目中使用Laravel6.5,所以我想我在使用Elount来实现它 Schema::create('games', function (Blueprint $table) { $table->bigIncrements('id');
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('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();
});
有没有确切的理由让我选择pivot表而不是2个外键?我觉得我还是一个通过有说服力的关系查询mysql数据库的新手。使用pivot表可以帮助您轻松建立多对多关系,并利用laravel各自的方法。
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();
});