Laravel-当父母改变时,如何更新所有的孩子



[我正在寻找处理的最佳实践]

我的数据结构如下:

Category Class
protected $fillable = [
'id', 'price', 'name'
];
public function products()
{
return $this->hasMany(Product::class, 'category_id');
}
Product Class 
protected $fillable = [
'category_id', 'price' 
];
public function category
{
return $this->belongsTo(Category::class, 'category_id');
}

假设我更新了类别的价格。所以,我想更新产品中与该类别表相关的所有价格,它也会更新与类别相同的价格

您有两个选项,要么使用

$table->foreignId('category_id')
->constrained()
->onUpdate('cascade');

或者,如果你不能改变你的数据库结构,使用模型观测器来更新它

根据您的示例,如果您想与模型关系一起使用。

$categorid = 5;
$newprice = '500';
Category::find($categorid)->products()->update(['price'=>$newprice]);

替代解决方案:当您需要执行级联更新时,有些方法指示在模型中使用静态方法。但是,有一种更简单的方法,并且在文档中没有明确说明

$table->unsignedBigInteger('category_id');
$table->foreign('category_id')->references('id')->on('categories')->onUpdate('cascade');

或者,使用约束方法(来自Laravel 7(:

$table->foreignId('category_id')->constrained()->onUpdate('cascade');

当父记录id发生更改时,它将更新子记录category_id

$category = Category::where('id', 'category-id')->first();
$category->products()->update(['price' => $category->price]);

最新更新