mafortis
mafortis

Reputation: 7128

Laravel Model relation

I want to make relation between 2 tables by third table like:

  1. Player can be signed to 1 team only.
  2. Team can have many players.

current relations

player model

public function teams()
    {
       return $this->belongsToMany(Team::class, 'team_players', 'team_id', 'player_id');
    }

team model

public function players()
    {
        return $this->belongsToMany(Player::class, 'team_players', 'team_id', 'player_id');
    }

more...

currently 1 player can be select for unlimited teams at the same time, what I want is 1 player = 1 team only. and if I detached player from that team then be able to sign it to another team.

How can i do that?

Upvotes: 0

Views: 46

Answers (2)

geoandri
geoandri

Reputation: 2428

I believe that in your case you need an one-to-many relationship between team and players. A team can "hasMany" many players while a player "belongsTo" a team. So for the team model

public function players()
{
    return $this->hasMany(Player::class);
}

and for the player model

public function team()
{
   return $this->belongsTo(Team::class);
}

In terms of database tables you only need a "team_id" field in the players table to hold the relationship.

Upvotes: 0

The Alpha
The Alpha

Reputation: 146191

Hope you've a pivot table team_players which contains at least team_players and team_id field. With that on mind, you should inverse the foreign keys in team model that you've currently, for example, change it to this:

public function players()
{
    return $this->belongsToMany(
        Player::class,
        'team_players',
        'player_id', // foreign key of this model
        'team_id' // foreign key of joining model
    );
}

The third argument is the foreign key name of the model on which you are defining the relationship, while the fourth argument is the foreign key name of the model that you are joining to. Check the documentation.

Upvotes: 1

Related Questions