我有一个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
谢谢。
-
你不需要
$table->unsignedBigInteger("current_season_id")->nullable();
在联赛表,如果你使用的是hasOne关系,否则你需要另一种类型的关系。 -
我强烈建议在季节表中,在迁移中使用外键声明
$table->unsignedBigInteger("league_id");
$table->foreign( 'league_id' )->references( 'id' )->on( 'leagues' );