3

For Laravel's polymorphic many to many relationship, how do you specify in the database migration that a database constraint should exist, for example, cascade down?

So for example, you have a Tag model that has a morphedByMany relationship with Products and a Product model that has morphToMany relationship with tags. Then having a polymorphic pivot table, how can you delete the mapping in the pivot table in case that product and/or tag is deleted.

There is a tags table, and a taggables table that is the pivot table that maps the tag to the taggable_type and the taggable_id.

Snippet from the Product model

/**
     * Tag relation
     *
     * @var $query
     */
    public function tags(){
        return $this->morphToMany(Tag::class, 'taggable')->withTimestamps();
    }

    /**
     * Tag relation
     *
     * @var $query
     */
    public function tag($tag){
        return $this->tags()->attach($tag);
    }

Snippet from the Tag model

/**
     * Product relation
     *
     * @var $query
     */
    public function products(){
        return $this->morphedByMany(Product::class, 'taggable')->withTimestamps();
    }

The taggables database migration

Schema::create('taggables', function (Blueprint $table) {
        $table->primary(['tag_id', 'taggable_id', 'taggable_type']); //This is to avoid duplicate  relationships

        $table->unsignedInteger('tag_id');
        $table->unsignedInteger('taggable_id');
        $table->string('taggable_type');

        $table->timestamps();
    });
Alexeia
  • 33
  • 6
  • 1
    Possible duplicate of [Laravel Eloquent ORM - Many to Many Delete Pivot Table Values left over](https://stackoverflow.com/questions/27330551/laravel-eloquent-orm-many-to-many-delete-pivot-table-values-left-over) – Salim Djerbouh Sep 23 '19 at 14:03

1 Answers1

2

Not sure how to achieve this with database constraints, but could you not make use of overriding the model's boot method? Such as including this in your Product model:

protected static function boot()
{
    parent::boot();

    static::deleting(function ($product) {
        $product->tags()->detach();
    });
}

This means whenever your product gets deleted, all related tags would be deleted as well.