Laravel 在与另一个同步(替换)时删除多对多关系数据的最安全方法

Laravel safest way to delete a many to many relationship data while sync (replace) with another

我有一个产品,类别关系是多对多的项目

// Product Model
public function categories()
{
   return $this->belongsToMany(Category::class);
}

//Category Model
public function products()
{
   return $this->belongsToMany(Product::class);
}

现在,当某个类别被删除时,我想将其产品分配给默认类别 (ID = 1)。 使用 Laravel 8

实现此目标的最佳方法是什么

您可能想尝试 deleting event:

class Category extends Model
{
    public static function booted()
    {
        static::deleting(function ($category) {
            $products = $category->products()->get();

            if ($products->isNotEmpty()) {
                $category->products()->detach();
                $defaultCategory = static::find(1);
                $defaultCategory->products()->sync($products->pluck('id')->toArray());
            }
            
        })
    }
}

感谢 Kevin

,我终于找到了解决方案
public static function boot()
{
    parent::boot();

    static::deleting(function ($category) {
        $products = $category->products;

        if ($products->isNotEmpty()) {
            $category->products()->detach();
            $defaultCategory = static::find(1);
            $defaultCategory->products()->sync($products->pluck('id')->toArray());
        }
        
    });
}