使用HasOne子关系更新父模型



我有一个League模型和一个Season模型,它们各自的迁移和关系。

League迁移与关系

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迁移与关系

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);
}

我的模型有两个变量:

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

有了这行,我知道Season模型中的league_id自动被$league->id填充。

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

我想做相反的,并填充current_season_id而不做:

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

有可能吗?

看了@M Khalid Junaid的评论,我觉得这样更好:

  • League模型中删除current_season_id
  • 重写current_season关系如下:
    public function current_season()
    {
    return $this->hasOne(Season::class)->where("is_current_season", true);
    }
    

现在,通过这种方式,我可以访问当前赛季的联赛:$league->current_season

谢谢。

  1. 你不需要$table->unsignedBigInteger("current_season_id")->nullable();在联赛表,如果你使用的是hasOne关系,否则你需要另一种类型的关系。

  2. 我强烈建议在季节表中,在迁移中使用外键声明

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

最新更新