在不更改父表值的情况下,雄辩地更新子表值

问题描述 投票:0回答:1

我的模型关系能够在更改父表值时更新子值。问题是如果父表没有进行更改,$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,并且当父表stockcode更改时,它将更新子表price的值。但是,如果父表的值不变,则子表stock的值不会被更新。

laravel eloquent laravel-4
1个回答
0
投票

您可以为此使用事件(https://laravel.com/docs/7.x/eloquent#events-using-closures

在您的Product模型中,您可以跟踪更新的事件并相应地修改您的子模型。

    protected static function booted()
    {
        static::updated(function ($product) {
            $product->branch->update([...]);
        });
    }
© www.soinside.com 2019 - 2024. All rights reserved.