Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

kazemimorteza68@gmail.com's avatar

define one foreign key have multiple refrence

Hi. i have three table Posts,Videos and Comments. one of column inside comment table have foreign key role. i want this foreign key have relation with two columns inside post and video.but migration only create one foreign key relation and can't create second relation.

Posts Table:


 Schema::create('posts', function (Blueprint $table) {
            $table->increments('p_id');
            $table->text("title");
            $table->text("body");
            $table->timestamps();
        });

Videos Table:


        Schema::create('videos', function (Blueprint $table) {
            $table->increments('v_id');
            $table->string("url");
            $table->text("title");
            $table->timestamps();
        });

Comments Table:


        Schema::create('comments', function (Blueprint $table) {
            
            $table->increments('c_id');
            $table->text("body");
            $table->integer("commentable_id")->unsigned();
            $table->string("commentable_type");
          $table->foreign('commentable_id')->references('v_id')->on('videos');
          
            $table->foreign('commentable_id')->references('p_id')->on('posts'); //Give Error
            $table->timestamps();
       
        });

when i want define second relation(foreign key) that give error.Please help me

0 likes
4 replies
cipsas's avatar

You don't need these lines:

 $table->foreign('commentable_id')->references('v_id')->on('videos');
 $table->foreign('commentable_id')->references('p_id')->on('posts'); //Give Error

You can't reverence one column to multiple tables

1 like
kazemimorteza68@gmail.com's avatar

@CIPSAS - Than you for reply. but i want create relation.if i delete two line i cannot create relation using Migration.

You can't reverence one column to multiple tables===> but inside phpmyadmion i can define and reference this subject . Thanks

Please or to participate in this conversation.