laravel 5.2 中的一列有 2 个外键

2 foreign keys on one column in laravel 5.2

这是我的数据库架构

我有这些型号:

我很困惑如何在模型中定义 matchesteams 之间的关系

这是我到目前为止所做的...

User.php

public function bets()
{
    return $this->hasMany('\App\Bet');
}

Bet.php

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

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

Match.php

public function bets()
{
    return $this->hasMany('\App\Bet');
}

//?????????????

Team.php

//?????????????


实际上我需要的是应该在 Team.phpMatch.php 中放置而不是 //???... 的代码,这样我就可以轻松地做这样的事情......

$team->matches();
$match->team1();
$match->team2();


谢谢

您可以指定每个关系的目标列:

public function team1() {
        return $this->belongsTo('\App\Match', 'team1_id');
    }
 public function team2() {
        return $this->belongsTo('\App\Match', 'team2_id');
    }

如果有帮助请告诉我。

应该是这样的:

Match.php

public function team1()
{
    return $this->belongsTo('\App\Team', 'team1_id');
}

public function team2()
{
    return $this->belongsTo('\App\Team', 'team2_id');
}

Team.php

public function matches()
{
    return $this->hasMany('\App\Match', 'team1_id')
                ->orWhere('team2_id', $this->id);
}

应该是这样的。试一试。

  1. Match.php

    public function team1(){
      return $this->belongsTo('App\Team', 'team1_id');
    }
    
    public function team2(){
      return $this->belongsTo('App\Team', 'team2_id');
    }
    
  2. Team.php

    public function matches1(){
      return $this->hasMany('App\Match', 'team1_id', 'id');
    }
    
    public function matches2(){
      return $this->hasMany('App\Match', 'team2_id', 'id');
    }