Johnny Builder
Johnny Builder

Reputation: 1

How can I set up Teams which have different positions for users as migrations and in Eloquent?

I am a student trying to get my head about the right migrations and model functions for the following setup:

I have teams which have different positions like top or mid (can be empty) and also an owner. I want to be able to use Eloquent to get:

  1. All teams where a user is the owner of ("$user->ownerOf"),
  2. all teams where a user is part of (position not needed, "$user->teams")
  3. all users which are part of a team ("$team->users")
  4. the user for every position ("$team->top")

EDIT: A user can be in multiple teams but only on one position in a given team

At the moment I use a table for the users without foreign keys and a table for the teams which has multiple foreign keys to the users table for the different positions. Below is my current create_teams_table migration:

 $table->bigIncrements('id');
 $table->string('name');
 $table->bigInteger('owner')->unsigned();
 $table->foreign('owner')->references('id')->on('users')->onDelete('cascade');
 $table->bigInteger('top_id')->nullable()->unsigned();
 $table->foreign('top_id')->references('id')->on('users')->onDelete('cascade');
 $table->bigInteger('jungle_id')->nullable()->unsigned();
 $table->foreign('jungle_id')->references('id')->on('users')->onDelete('cascade');

There are more positions but I think this should be enough to understand the concept.

I can get the different users for the positions in my Team-Model with

public function ownerUser()
{
    return $this->belongsTo('App\Models\User', 'owner');
}

But I can't find a way to get every user in a team (like $team->users). Is there a better solution to the whole setup to begin with? For example a new table?

Thanks in advance!

Upvotes: 0

Views: 28

Answers (1)

spartyboy
spartyboy

Reputation: 426

public function users(){
  return $this->hasMany(Users::class,'team_id','id');
}

Upvotes: 0

Related Questions