简体   繁体   中英

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();
    });

This should delete the record on the pivot table if you delete the item on table: $tablename->foreign('taggable_id') ->references('taggable_type')->on('tags') ->onDelete('cascade');

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM