我的模型关系能够在更改父表值时更新子值。问题是如果父表没有进行更改,$model->save()
将不会更新子表。
产品型号关系(父级)
public function branch()
{
return $this->hasOne('BranchProduct')->where('branch_product.id', 'id');
}
BranchProduct模型关系(子级)
public function product()
{
return $this->hasOne('Product', 'id', 'product_id');
}
样本代码
$instance = Product::findOrFail(1);
$instance->fill('code, price');
$instance->save();
假设子表具有列stock
,并且当父表stock
或code
更改时,它将更新子表price
的值。但是,如果父表的值不变,则子表stock
的值不会被更新。
您可以为此使用事件(https://laravel.com/docs/7.x/eloquent#events-using-closures)
在您的Product
模型中,您可以跟踪更新的事件并相应地修改您的子模型。
protected static function booted()
{
static::updated(function ($product) {
$product->branch->update([...]);
});
}