Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
125 views
in Technique[技术] by (71.8m points)

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

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 AppModelsProductFeatureVariant::sync()'

What is the right approach here?

question from:https://stackoverflow.com/questions/65896662/what-is-best-way-to-detach-on-a-deep-relationship-relationships-of-relationsip

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...