2016-01-23 79 views
1

我很想用一種乾淨的方式在Laravel之間建立三種模型之間的工作關係。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」設置更多表格?

回答

0

根據您的比賽模式,我可能會修改您的匹配關係如下:

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

不錯!不知道這種關係是以這種方式工作的,對多個索引使用多個類。我想還有更多... :-) – Bensen

+0

:)我希望它有幫助。與您的項目一切順利! – Rick