what is best way to detach on a deep relationship (relationships of relationsip)?

Viewed 46

I have a product which belongsToMany features which belongsToMany variants.

Product

public function features()
{
    return $this->belongsToMany(Feature::class, 'product_feature', 'product_id', 'feature_id');
}

Feature

public function variants()
{
    return $this->belongsToMany(Variant::class, 'feature_variant', 'feature_id', 'variant_id');
}

Here the variant relation depends on feature relation. If the feature relation is removed the related variant relations should be removed as well. What is the best way to do that?

I tried this

$product->features()->each(function($feature){
    $feature->variants()->each(function($variant){
       $variant->sync([]); // $variant()->sync([]) returns Function name must be a string in...
    });
});

but get BadMethodCallException with message 'Call to undefined method App\Models\ProductFeatureVariant::sync()'

What is the right approach here?

1 Answers

I think the best id is use cascade and it will be what you want automaticly

$table->foreign('feature')->references('id')->on('variant')->onDelete('cascade');

You can read more about cascade in this link

Related