简体   繁体   中英

Laravel Many to Many relation Cannot add foreign key constraint

I'm creating a ManyToMany relationship with the Laravel framework v.5.7. So I created three migrations.

Modules Table

Schema::create('modules', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name')->unique();
    $table->integer('price');
});

Plans Table

Schema::create('plans', function (Blueprint $table) {
    $table->increments('id');
    $table->string('stripe_id')->unique();
    $table->integer('price');
    $table->integer('max_users');
    $table->timestamps();
});

Relation Table

Schema::create('plan_modules', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('plan_id')->unsigend();
    $table->integer('module_id')->unsigend();
    // Keys
    $table->foreign('plan_id')->references('id')->on('plans')->onDelete('cascade');
    $table->foreign('module_id')->references('id')->on('modules')->onDelete('cascade');
});

Whe I run the migration I get General error: 1215 Cannot add foreign key constraint .

Dose anyone has a idea what is wrong with the migrations. The default engine for mysql is set to InnoDB .

Your last migration should be as follows:

Schema::create('plan_modules', function (Blueprint $table) {
    $table->increments('id');
    $table->unsignedInteger('plan_id')
    $table->unsignedInteger('module_id');
    $table->foreign('plan_id')->references('id')->on('plans')->onDelete('cascade');
    $table->foreign('module_id')->references('id')->on('modules')->onDelete('cascade');
});

Fixed the typos and you need to apply onDelete() to the foreign key definition and not the actual field definition.

Provided that your migration run in the same order you mentioned above, it should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM