Home > Software design >  Can't create table `issue`.`section_comments
Can't create table `issue`.`section_comments

Time:10-23

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

CodePudding user response:

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

It should work, sorry if I’m wrong since I’m using phone

  • Related