2016-11-29 156 views
0

我为玩家创建系统。
我有以下3个表:Laravel创建表和关系

matches: 
    - id 
    - win_points 
    - draw_points 
    - lose_points 

aways: 
    - id 
    - match_id 
    - user_id 
    - score 

homes: 
    - id 
    - match_id 
    - user_id 
    - score 

现在我有一些问题的关系。
我可以得到用户,得到他的客户,但我不能得到有关比赛的信息。

我想透视表away_match和home_match,但我不知道这是否是个好主意。

+1

你不需要一个数据透视表,你已经有了一个可以用来创建关系的外键,即* user *'hasMany()'aways和homes。 laravel.com/docs/5.3/eloquent-relationships#one-to-many不要忘记在构建迁移时定义关系:'$ table-> fo reign('user_id') - >引用('id') - > on('users');'(更多详细信息,请参阅* Schema Builder *文档)。 – user2693053

回答

1

你不需要任何枢轴。 在型号防范和家庭,你可以添加以下功能:

public function match(){ 
    return $this->belongsTo(Match::class); 
} 

它将返回客场/主页的比赛。与documentation不同,我在这里使用了Match :: class,它只有在您将名称空间设置为App \ Models而不仅仅是App时才有效。

从用户现在可以得到与之相匹配的这段代码:

$match = $user->homes->find($homeId)->match; 

(你从你的用户说,你可以得到家庭和跳投,所以我假设你已经在实施类似的方法用户模型

public function homes(){ 
    return $this->hasMany(Home::class); 
} 
+0

这对我来说是最好的答案。一切运作良好。 –

+0

很高兴有帮助。 – Cashbee

0

至于我的理解,您可以使用matchplayers表中的Many to Many Relationship

你可以考虑你的数据库结构是这样的:

players 
    - id 
    - name 
    - ... 

matches 
    - id 
    - name 
    - ... 

match_player 
    - id 
    - player_id 
    - match_id 
    - match_type (either - home match or away match) 
    - win_points 
    - lose_points 
    - ... 

模型和关系会像:

class Player extends Model 
{ 
    public function matches() 
    { 
     return $this->belongsToMany(Match::class, 'match_player') 
        ->withPivot(['match_type', 'win_points', 'lose_points']); 
    } 
} 

class Match extends Model 
{ 
    public function players() 
    { 
     return $this->belongsToMany(Player::class, 'match_player') 
        ->withPivot(['match_type', 'win_points', 'lose_points']); 
    } 
} 

希望这有助于!