【问题标题】:Use two tables on a two-to-many relationship or use three tables with a pivot table在二对多关系上使用两个表或将三个表与数据透视表一起使用
【发布时间】:2020-03-22 13:06:12
【问题描述】:

基本上,我的数据库中有 2 个表:Games 和 Teams。

每场比赛必须有 2 支球队,所以这是一对多的关系。

我应该在我的 Games 表中使用 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();
        });

这是我现在创建的两个表,这是实现它的正确方法吗?

【问题讨论】:

    标签: php mysql database laravel eloquent


    【解决方案1】:

    使用多对多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();
      });
    

    【讨论】:

    • 有什么确切的理由我应该使用数据透视表方式而不是 2 个外键方式吗?在通过雄辩和关系查询mysql数据库方面,我觉得我还是个新手。
    • 使用数据透视表可以帮助您轻松建立多对多关系,并利用 laravel 各自的方法。
    猜你喜欢
    • 2020-04-15
    • 1970-01-01
    • 2011-08-10
    • 2016-02-02
    • 2020-06-24
    • 1970-01-01
    • 2014-06-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多