Laravel Relationship: A division has many ranks, a rank has 1 division, and a user has only 1 rank

Viewed 92

For instance:

Divisions:

  • Division A
  • Division B
  • Division C
  • etc...

Ranks in Divisions

  • Division A -- Rank 1, Rank 2, Rank 3, ...
  • Division B -- Rank a, Rank b, Rank c, ...
  • etc..

And a user would only be assigned a rank. For instance, they would be "Rank 1".

Exactly what type of relationship would this scenario require? And how would the tables setup have to look like?

1 Answers

Your division table would be

id | name

Your rank table would be

id | division_id | name

your user table would be

id | name

your user_rank table would be

id | user_id | rank_id

As per relationship in Laravel

Division Model

class Division extends Model
{
    protected $table = 'divisions';
    public function ranks()
    {
        return $this->hasMany('App\Rank','rank_id','id');
    }
}

Rank Model

class Rank extends Model
{
    protected $table = 'ranks';
    public function divison()
    {
        return $this->belongsTo('App\Divison','rank_id','id');
    }
    public function users()
    {
        return $this->belongsToMany('App\User',''user_rank','rank_id','user_id');
    }
}

User Model

class User extends Model
{
    protected $table = 'users';
   
    public function ranks()
    {
        return $this->belongsToMany('App\Rank',''user_rank','user_id','rank_id');
    }
}
Related