Can't create table `issue`.`section_comments

Issue

Can’t create table issue.section_comments on migration

SQLSTATE[HY000]: General error: 1005 Can't create table `issue`.`section_comments` 
(errno: 150 "Foreign key constraint is incorrectly formed") 
(SQL: alter table `section_comments` add constraint `section_comments_parent_id_foreign` foreign key (`parent_id`) references `petition_comments` (`id`))

migration

  public function up()
    {
        Schema::create('section_comments', function (Blueprint $table) {
            $table->id();
            $table->foreignId('petition_id')->constrained();
            $table->text('comment_text');
            $table->foreignId('parent_id')->nullable()->references('id')->on('section_comments');
            $table->timestamps();
        });
    }

Solution

Firstly, you should change it to like this;

$table->foreignId('petition_id')->constrained(‘petitions’);

Delete this line;

$table->foreignId('parent_id')->nullable()->references('id')->on('section_comments');

Add a new migration file or add below code after Schema::create;

Schema::table('section_comments', function (Blueprint $table) {
$table->foreignId('parent_id')->nullable()->constrained('section_comments’);
});

Answered By – kdrmlhcn

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published