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