bobD
bobD

Reputation: 1077

2 foreign keys on one column in laravel 5.2

here's my database schema

enter image description here

and I have these models:

I'm confused how to define the relationShip between matches and teams in models

here Is what I did till now...

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

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


actually what I need Is the code that should be placed instead of //???... in both Team.php and Match.php so that I can easily do such things...

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


thanks

Upvotes: 0

Views: 285

Answers (3)

Mihai Matei
Mihai Matei

Reputation: 24276

It should be something like this:

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

Upvotes: 2

Abdullah Al Shakib
Abdullah Al Shakib

Reputation: 2044

It would be something like this. Give it a try.

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

Upvotes: 0

J3Rik0
J3Rik0

Reputation: 11

You can specify which column should be targeted for each relationship:

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

Let me know if this helps.

Upvotes: 0

Related Questions