2

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?

Brennan
  • 35
  • 1
  • 6

1 Answers1

3

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');
    }
}
Dilip Hirapara
  • 14,810
  • 3
  • 27
  • 49
  • 1
    If a rank can be assigned to multiple users, would it not be necessary to instead use $this->hasMany(User::class, 'user_id', 'id') and have a rank() function in the Users Model as well? I'm still grasping onto Laravel, so pardon me. – Brennan Jul 24 '20 at 04:01
  • 1
    @Brennan if a user can have only one rank, as indicated in the question, it should be hasOne instead of hasMany. But yes, you are right about having the rank relationship in user model – user3532758 Jul 24 '20 at 04:03
  • 1
    @user3532758 Ah okay, so what I'm getting at is that this answer is correct (it does seem logical to me, at least), though what's missing is essentially is this function in the User model: public function rank() { return $this->hasOne('App\Rank', 'rank_id', 'id'); } – Brennan Jul 24 '20 at 04:08
  • User has Many rank then it would be belogsToMany relation please check my edited answer. – Dilip Hirapara Jul 24 '20 at 04:08
  • I have edited the answer as per your requirement, if users have many ranks then it should be belongsTomany. If user have only one rank then it should be `hasone,belongsTo`. – Dilip Hirapara Jul 24 '20 at 04:12