Reputation: 137
I create system for players.
I have the following 3 tables:
matches:
- id
- win_points
- draw_points
- lose_points
aways:
- id
- match_id
- user_id
- score
homes:
- id
- match_id
- user_id
- score
Now I have some problem with relations.
I can get user, get his aways,homes but I can't get then info about match.
I am thinking about pivot table for away_match and home_match but I don't know if it's good idea.
Upvotes: 0
Views: 168
Reputation: 5766
You don't need any pivots. in the Models Away and Home you can add the following function:
public function match(){
return $this->belongsTo(Match::class);
}
Which will return the match of the Away/Home. Unlike in the documentation, i here used Match::class which only works if you set the namespace to App\Models and not just App.
from the user you can now get the match with this piece of code:
$match = $user->homes->find($homeId)->match;
(you said from your user you can get homes and aways, so i assume you already implemented a similar method in the User Model
public function homes(){
return $this->hasMany(Home::class);
}
Upvotes: 1
Reputation: 13699
As upto my understanding, you can use the Many to Many Relationship between match
and players
table.
You can consider your DB structure in this way:
players
- id
- name
- ...
matches
- id
- name
- ...
match_player
- id
- player_id
- match_id
- match_type (either - home match or away match)
- win_points
- lose_points
- ...
The Model and relationships would be like:
class Player extends Model
{
public function matches()
{
return $this->belongsToMany(Match::class, 'match_player')
->withPivot(['match_type', 'win_points', 'lose_points']);
}
}
class Match extends Model
{
public function players()
{
return $this->belongsToMany(Player::class, 'match_player')
->withPivot(['match_type', 'win_points', 'lose_points']);
}
}
Hope this helps!
Upvotes: 0