![](/img/trans.png)
[英]Migration for self referencing many to many relation failing in Laravel with "Foreign key constraint is incorrectly formed"
[英]Laravel Many to Many relation Cannot add foreign key constraint
我正在使用Laravel框架v.5.7創建ManyToMany關系。 因此,我創建了三個遷移。
模塊表
Schema::create('modules', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->unique();
$table->integer('price');
});
計划表
Schema::create('plans', function (Blueprint $table) {
$table->increments('id');
$table->string('stripe_id')->unique();
$table->integer('price');
$table->integer('max_users');
$table->timestamps();
});
關系表
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');
});
運行遷移時,出現General error: 1215 Cannot add foreign key constraint
。
劑量任何人都知道遷移有什么問題。 mysql的默認引擎設置為InnoDB
。
您的上一次遷移應如下所示:
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');
});
修復了輸入錯誤,您需要將onDelete()
應用於外鍵定義,而不是實際的字段定義。
前提是您的遷移按上述順序運行,那么它應該可以正常工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.