简体   繁体   English

Laravel多对多关系无法添加外键约束

[英]Laravel Many to Many relation Cannot add foreign key constraint

I'm creating a ManyToMany relationship with the Laravel framework v.5.7. 我正在使用Laravel框架v.5.7创建ManyToMany关系。 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 . 运行迁移时,出现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 . mysql的默认引擎设置为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. 修复了输入错误,您需要将onDelete()应用于外键定义,而不是实际的字段定义。

Provided that your migration run in the same order you mentioned above, it should work. 前提是您的迁移按上述顺序运行,那么它应该可以正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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