1

I have table category which have parent of type of itself.

Schema::create('categories', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->integer('parent_id')->unsigned()->nullable()->default(null);
        $table->foreign('parent_id')->references('id')->on('categories');
        $table->timestamps();
    });

Throws:

SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `categories` add constraint `categories_parent_id_foreign` foreign key (`parent_id`) references `categories` (`id`))

I've already tried making parent_id as foreign in seperate, Schema::table function yet with no success. Table is InnoDB type.

3
  • why are you creating a FK that references the same table that you're creating? parent_id should reference id on the parents table Commented Mar 9, 2019 at 15:21
  • 1
    As I mentioned in first line, categories have parents of categories Commented Mar 9, 2019 at 15:27
  • Oh, my bad. I didnt see it. Commented Mar 9, 2019 at 15:52

1 Answer 1

2

Try changing your FK from integer to bigInteger:

$table->bigInteger('parent_id')->unsigned()->nullable()->default(null);

or

$table->unsignedBigInteger('parent_id')->nullable()->default(null);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.