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
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
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
You can create relation through Model's like here https://laravel.com/docs/5.7/eloquent-relationships#one-to-one-polymorphic-relations
But you can't strict polymorph relation on DB side.
Please or to participate in this conversation.