【问题标题】:Laravel relationships and indexes between Matches, Teams, Players比赛、球队、球员之间的 Laravel 关系和索引
【发布时间】:2016-01-23 17:58:07
【问题描述】:

我正在努力考虑使用一种干净的方式在 Laravel 中设置三个模型之间的工作关系。

有大量的比赛,其中总是包含2支球队,每支球队都有5名球员
注意:玩家不是用户,所以每场比赛都会产生新的球队和球员。

匹配项

class Match extends Model
{
    public function teams()
    {
        return $this->hasMany('App\Team');
    }
}

团队

class Team extends Model
{
    public function players()
    {
        return $this->hasMany('App\Player');
    }

    public function match()
    {
        return $this->belongsTo('App\Match');
    }
}

玩家

class Player extends Model
{
    public function team()
    {
        return $this->belongsTo('App\Team');
    }
}

我的问题是我在可爱的 Laravel 文档中找不到使用具有两个索引的数据库表的解决方案。
具体:比赛条目有一个获胜者和一个较松的球队。如何用雄辩的方式告诉 Laravel?

匹配项

    Schema::create('matches', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('winner_team_id')->index();
        $table->integer('looser_team_id')->index();

团队

    Schema::create('teams', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('player_1')->index();
        $table->integer('player_2')->index();
        $table->integer('player_3')->index();
        $table->integer('player_4')->index();
        $table->integer('player_5')->index();

玩家

    Schema::create('players', function (Blueprint $table) {
        $table->increments('id');

这种方法“不干净”还是我错过了文档中明显的一些东西,比如模型的更多基于关系的类?

我是否必须为 manyToMany-relationships-approach 设置更多表,例如“match_teams”和“team_players”?

【问题讨论】:

    标签: database laravel


    【解决方案1】:

    根据您的匹配架构,我可能会修改您的匹配关系如下:

    class Match extends Model
    {
        public function teamA()
        {
            return $this->hasOne('App\Team');
        }
    
        public function teamB()
        {
            return $this->hasOne('App\Team');
        }
    
        public function winningTeam()
        {
            return $this->hasOne('App\Team');
        }
    }
    

    假设您的比赛总是恰好包含两支球队。然后在您的架构中:

    Schema::create('matches', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('teama_id')->index();
        $table->integer('teamb_id')->index();
        $table->integer('winningteam_id')->index(); // Loser team is one of the ids from above ID, you would write a query scope to return the loser team.
        $table->string('result');
    }
    

    【讨论】:

    • 不错!不知道关系以这种方式工作,对多个索引使用多个类。我想还有更多... :-)
    • :) 我希望它有所帮助。祝您的项目一切顺利!
    猜你喜欢
    • 2022-06-25
    • 1970-01-01
    • 2022-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-09
    • 2018-05-27
    相关资源
    最近更新 更多