使用 HasOne 子关系更新父模型

时间:2021-01-20 19:16:45

标签: php laravel eloquent eloquent-relationship

我有一个 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);

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

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

我想做相反的事情,并在不做的情况下填充 current_season_id

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

有可能吗?

2 个答案:

答案 0 :(得分:1)

根据@M Khalid Junaid 的评论,我认为这样更好:

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

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

谢谢。

答案 1 :(得分:0)

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

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

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