laravel 5.2中一列上的2个外键

时间:2016-09-06 12:28:00

标签: php database laravel laravel-5.2 database-relations

这是我的数据库架构

enter image description here

我有这些模型:

  • 管理
  • 用户
  • 赌注
  • 匹配

我很困惑如何定义模型中matchesteams之间的relationShip 这是我到现在为止所做的......

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.php中应该放置的代码而不是Match.php,以便我可以轻松地执行此类操作...

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


感谢

3 个答案:

答案 0 :(得分:2)

它应该是这样的:

<强> 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 :(得分:0)

您可以指定每个关系应定位的列:

Model[i]

如果有帮助,请告诉我。

答案 2 :(得分:0)

会是这样的。试一试。

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