【问题标题】:Eloquent how to update child table value while parent table value is not change雄辩的如何在父表值不变的情况下更新子表值
【发布时间】:2020-04-28 08:57:41
【问题描述】:

我的模型关系能够在父表值更改时更新子值。问题是$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,当父表codeprice发生变化时,它会更新子表stock的值。但是,当子表stock 值不会被更新时,如果父值没有改变。

【问题讨论】:

  • codeprice 相比,更新stock 背后的逻辑是什么?
  • 当心你的人际关系不是这样运作的。您不会添加 hasOne 两次,而只会添加一个关系(没有外键的关系)。此外,您对 branch_product 的命名是分支和产品之间多对多关系的保留措辞。最重要的是,您的where(...) 条件正在检查字符串id,这可能不是您想要的。您应该省略 where 条件。如果要命名应用于关系的列,可以在 hasOne 函数中进行。此外,您的 fill('code, price') 也不起作用。
  • 抱歉长评论。 fillupdate 一样,需要一个关联数组,其中数组键是您要更新的列。您应该先尝试遵循一些教程并阅读文档。看看laracasts.com/series/laravel-6-from-scratch

标签: laravel eloquent laravel-4


【解决方案1】:

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

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

    protected static function booted()
    {
        static::updated(function ($product) {
            $product->branch->update([...]);
        });
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-20
    • 1970-01-01
    • 2023-03-04
    • 2017-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多