Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For laravel polymorphic manytomany relationships, how do you add database constraints?

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();
    });
like image 918
Alexeia Avatar asked Dec 22 '25 15:12

Alexeia


1 Answers

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.

like image 68
Jason Hodkinson Avatar answered Dec 24 '25 07:12

Jason Hodkinson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!