使用 HasOne 子关系更新父模型
Update parent model with the HasOne child 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();
可能吗?
根据@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
谢谢。
你不需要$table->unsignedBigInteger("current_season_id")->nullable();
在联盟table,如果你使用hasOne关系,否则你需要另一种类型的关系。
我强烈建议在季节 table 中使用迁移中的外键声明
$table->unsignedBigInteger("league_id");
$table->foreign( 'league_id' )->references( 'id' )->on( 'leagues' );
我有一个 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();
可能吗?
根据@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
谢谢。
你不需要
$table->unsignedBigInteger("current_season_id")->nullable();
在联盟table,如果你使用hasOne关系,否则你需要另一种类型的关系。我强烈建议在季节 table 中使用迁移中的外键声明
$table->unsignedBigInteger("league_id");
$table->foreign( 'league_id' )->references( 'id' )->on( 'leagues' );