【问题标题】:2 foreign keys on one column in laravel 5.2laravel 5.2中一列上有2个外键
【发布时间】:2017-01-13 21:55:12
【问题描述】:

这是我的数据库架构

我有这些模型:

  • 管理员
  • 用户
  • 下注
  • 匹配
  • 团队

我很困惑如何在模型中定义 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();


谢谢

【问题讨论】:

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


    【解决方案1】:

    应该是这样的:

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

    【讨论】:

    • 不起作用...,我这样做了return dd($team->matches()->where('id' ,'=', 1)->get());,这是错误找不到基表或视图:1146 表'football_bet.match_team'不存在
    • 刚刚编辑过..你能再验证一下吗? dd($team->matches()->find(1))
    【解决方案2】:

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

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

    如果这有帮助,请告诉我。

    【讨论】:

      【解决方案3】:

      应该是这样的。试试看吧。

      1. Match.php

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

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

      【讨论】:

      • 工作没问题,谢谢,但我如何才能访问球队参加的所有比赛?不管是一队还是二队,都是唯一的加入数组结果的方法吗?
      • 与()一起使用。例如:Team::with('matches1', 'matches2')。要了解更多信息,请查看stackoverflow.com/questions/30231862/…
      猜你喜欢
      • 2017-01-16
      • 2016-06-06
      • 1970-01-01
      • 1970-01-01
      • 2017-01-18
      • 2015-10-17
      • 1970-01-01
      • 2020-12-30
      • 1970-01-01
      相关资源
      最近更新 更多