Search code examples
phplaraveleloquenteloquent-relationship

Update parent model with the HasOne child relationship


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?


Solution

  • 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.