1

I have a League model and a Season model their respective migrations and relationships.

League migration and relations

Schema::create('leagues', function (Blueprint $table) {
    $table->unsignedBigInteger("id")->primary();
    $table->boolean("active");
    $table->string("name");
    $table->unsignedBigInteger("current_season_id")->nullable();
    $table->timestamps();
});
public function current_season()
{
    return $this->hasOne(Season::class);
}

Season migration and relations

Schema::create('seasons', function (Blueprint $table) {
    $table->unsignedBigInteger("id")->primary();
    $table->string("name");
    $table->unsignedBigInteger("league_id");
    $table->boolean("is_current_season");
    $table->timestamps();
});
public function league()
{
    return $this->belongsTo(League::class);
}

I have two vars with my models:

$league = League::find(1);
$season = Season::find(10);

With this line, I know automatically league_id in the Season model is filled with the $league->id

$season->league()->associate($league)->save();

I want do the inverse, and fill the current_season_id without doing:

$league->current_season_id = $season->id;
$league->save();

Is it possible?

Randolf
  • 367
  • 1
  • 14
  • 1
    It is possible , but I can see a circular reference issue in your models this can be tricky if you have foreign keys and when you try to delete record from any of your model it will throw exception and then you have to perform deletion in 2 steps , first remove reference then delete – M Khalid Junaid Jan 20 '21 at 19:32
  • Do you have any proposal or other way to do it to improve it? – Randolf Jan 20 '21 at 20:01
  • 1
    You already have `is_current_season` bit in your seasons table , I believe it is per league so you don't need `current_season_id` in your league table – M Khalid Junaid Jan 20 '21 at 20:05
  • You see it better with my answer? – Randolf Jan 20 '21 at 20:16

2 Answers2

2

Following the comments from @M Khalid Junaid, I think it´s better this way:

  • Remove current_season_id from League model.
  • Rewrite the current_season relation to this way:
    public function current_season()
    {
         return $this->hasOne(Season::class)->where("is_current_season", true);
    }
    

Now, in this way, I can access the current season of the league in the form: $league->current_season

Thank you.

Randolf
  • 367
  • 1
  • 14
0
  1. You do not need $table->unsignedBigInteger("current_season_id")->nullable(); in leagues table, if you are using hasOne relationship, otherwise you need another type of relationship.

  2. I'd strong recommend in seasons table, to use a foreign key declaration in your migration

$table->unsignedBigInteger("league_id");
$table->foreign( 'league_id' )->references( 'id' )->on( 'leagues' );
BQRoster
  • 21
  • 1