2016-11-30 27 views
2

我是Laravel的新手(僅編寫了幾個月)。我創建了一個DB模型,通過數據透視表連接兩個表「玩家」和「團隊」。玩家可以是(許多)團隊的成員,「自己」的團隊,被「招募」到團隊中,並被團隊「拒絕」。球隊和球員都可以針對這些狀態發起請求,允許對方確認/拒絕。在每種情況下,它們都應該鏈接並且只能佔據四種狀態之一。鏈接這兩個表的最好方法是什麼,以便任何兩個實例之間的關係可以被賦予4個「狀態」?Laravel數據模型中的多個2關表關係的多個「狀態」?最佳方法?

我需要給用戶(在這個開放的管理/招聘環境中的控制團隊和參與者),在每個「狀態」中請求/批准分類的能力。

這讓我感到最乾淨的方法是使用一個數據透視表,將這些給定的狀態「分配」給每個鏈接的ID對。但是,我只看到了這個概念的更簡單的例子,因此我不確定最好的方法是什麼。我希望這裏有一些指導。

Schema::create('player_team', function (Blueprint $table) { 

    $table->increments('id'); 
    $table->timestamps(); 

    # `book_id` and `tag_id` will be foreign keys, so they have to be unsigned 
    # Note how the field names here correspond to the tables they will connect... 
    # `book_id` will reference the `books table` and `tag_id` will reference the `tags` table. 
    $table->integer('player_id')->unsigned(); 
    $table->integer('team_id')->unsigned(); 

    # Make foreign keys 
    $table->foreign('player_id')->references('id')->on('players'); 
    $table->foreign('team_id')->references('id')->on('teams'); 
}); 

*再次,我很新鮮。道歉,如果這有一個明顯的解決方案,我只是想念。

回答

1

如果我理解正確的話,你可以添加status列透視表:

$table->tinyInteger('status')->unsigned(); 

不要忘記添加withPivot()到關係:

return $this->belongsToMany('p4\Player')->withPivot('status')->withTimestamps(); 

你可以訪問此列pivot並通過向attach()detach()方法添加數組來設置或取消設置:

$team->players()->attach($playerId, ['status' => 3]); 

閱讀文檔更多關於它:

https://laravel.com/docs/5.3/eloquent-relationships#many-to-many https://laravel.com/docs/5.3/eloquent-relationships#inserting-and-updating-related-models

+1

謝謝你,我感謝幫助了很多:) –

+0

你知道過濾我得到執行下列操作結果的正確方法?我不能在哪裏使用,而且文檔不清晰。 foreach($ player-> teams as $ team){ if($ team-> pivot-> status == 2){player_teams [] = $ team; } } –

相關問題