0

here's my database schema

enter image description here

and I have these models:

  • Admin
  • User
  • Bet
  • Match
  • Team

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

bobD
  • 1,037
  • 2
  • 9
  • 17

3 Answers3

2

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);
}
Mihai Matei
  • 24,166
  • 5
  • 32
  • 50
  • doesn't work..., I did this `return dd($team->matches()->where('id' ,'=', 1)->get());` and this is the error **Base table or view not found: 1146 Table 'football_bet.match_team' doesn't exist** – bobD Sep 06 '16 at 12:53
  • Just edited.. can you please verify it again? `dd($team->matches()->find(1))` – Mihai Matei Sep 06 '16 at 13:10
0

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.

J3Rik0
  • 11
  • 1
  • 3
0

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');
    }
    
Abdullah Al Shakib
  • 2,034
  • 2
  • 15
  • 16
  • work's fine, thank you , but how can I access all the matches that the team was In? no matter It was the first team or second one , Is It the only way to join the array results? – bobD Sep 06 '16 at 13:08
  • Use with(). example: Team::with('matches1', 'matches2'). to learn more check this http://stackoverflow.com/questions/30231862/laravel-eloquent-has-with-wherehas-what-do-they-mean – Abdullah Al Shakib Sep 07 '16 at 10:19