Reputation: 35
I face a problem implementing some Database ERs in Laravel. The problem is present for both "1-1" and "1-N" relationships.
The example bellow is pretty straightforward I think.
We have a "Team" And a "Player"
One Team Has Many Players. The problem comes in case I need to keep extra info for that relationship.
An example would be "The Player Plays for that team from Date_1 to Date_2".
In this example it seems that we need an extra table to keep this kind of info. As I know Laravel does not use pivot tables for "1-1" or "1-N".
So, how would we implement this case the Laravel way..?
Upvotes: 2
Views: 856
Reputation: 2191
This is a tricky one. But I would ad one more table called player_records. With the following attributes
player_id
team_id.
start_date
end_date
In each model I would have helper methods to get for example active players.
Here is the Team model.
class Team extends Model
{
public function playerRecords() {
return $this->hasMany(PlayerRecord::class);
}
public function activePlayers() {
return $this->playerRecords()->where('start_at', '<=', Carbon::now())->where('ends_at', '>=', Carbon::now())->with('player')->get()->pluck('player');
}
}
Here is the Player model
class Player extends Model
{
public function playerRecords() {
return $this->hasMany(PlayerRecord::class);
}
}
And here is the PlayerRecord model
class PlayerRecord extends Model
{
public function player() {
return $this->hasMany(Player::class);
}
}
Upvotes: 2