Php 更新具有一个子关系的父模型

Php 更新具有一个子关系的父模型,php,laravel,eloquent,eloquent-relationship,Php,Laravel,Eloquent,Eloquent Relationship,我有一个联盟模型和一个赛季模型,它们各自的迁移和关系 联盟迁移与关系 Schema::create('leagues',函数(Blueprint$表){ $table->unsignedBigInteger(“id”)->primary(); $table->boolean(“活动”); $table->string(“名称”); $table->unsignedBigInteger(“当前季节id”)->nullable(); $table->timestamps(); }); 公共功能本季

我有一个
联盟
模型和一个
赛季
模型,它们各自的迁移和关系

联盟
迁移与关系

Schema::create('leagues',函数(Blueprint$表){
$table->unsignedBigInteger(“id”)->primary();
$table->boolean(“活动”);
$table->string(“名称”);
$table->unsignedBigInteger(“当前季节id”)->nullable();
$table->timestamps();
});
公共功能本季()
{
返回$this->hasOne(季节::类);
}
季节
迁移与关系

Schema::create('seasures',函数(Blueprint$表){
$table->unsignedBigInteger(“id”)->primary();
$table->string(“名称”);
$table->unsignedBigInteger(“联盟id”);
$table->boolean(“是当前季节”);
$table->timestamps();
});
公共职能联盟()
{
返回$this->belongsTo(联盟::类);
}
我的模型有两个变量:

$league=league::find(1);
$season=季节::查找(10);
有了这行代码,我自动知道
league\u id
赛季
模型中填充了
$league->id

$seasure->league()->associate($league)->save();
我想做相反的操作,并填写
当前\u季节\u id
,而不执行以下操作:

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

有可能吗?

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

  • League
    模型中删除
    current\u season\u id
  • 按照以下方式重写当前季节的关系:
    公共功能本季()
    {
    return$this->hasOne(seasure::class)->where(“is\u current\u seasure”,true);
    }
    
现在,通过这种方式,我可以以如下形式访问联赛的当前赛季:
$league->current_seash

多谢各位

  • 您不需要
    $table->unsignedbiginger(“当前季节id”)->nullable()
    在leagues表中,如果您使用的是一种关系,则需要另一种类型的关系

  • 在表中,我强烈建议在迁移中使用外键声明


  • 这是可能的,但我可以在您的模型中看到一个循环引用问题。如果您有外键,这可能会很棘手,当您尝试从任何模型中删除记录时,它将引发异常,然后您必须分两步执行删除,首先删除参考然后删除你有什么建议或其他方法来改进它吗?你的赛季表中已经有了
    is\u current\u seasure
    位,我相信它是每个联赛的,所以你不需要
    current\u seasure\u id
    在你的联赛表中你看得更清楚吗?是的,这样更好,付出了很大的努力
    $table->unsignedBigInteger("league_id");
    $table->foreign( 'league_id' )->references( 'id' )->on( 'leagues' );