Many To Many DB unique constrains

  • Posted on: 10 December 2019
  • By: stillfinder

Let us have 2 tables - “posts” and “tags”. In addition, we have a table called 'post_tag' for many-to-many relationships. To make sure the post <-> tag is unique, we can use the following code in create_post_tag_table.php:

    public function up()
    {
            $table->unique(['post_id', 'tag_id']);
 
            // delete table row when deleting post
            $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade'); 
 
            // delete table row when deleting tag
            $table->foreign('tag_id')->references('id')->on('tags')->onDelete('cascade'); 
// ...