![](/img/trans.png)
[英]Laravel 6: SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
[英]SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint Laravel 5.4
我有一個Laravel遷移無法解決的問題。
這是我的用戶遷移,數據名稱為:2014_12_10_000000_create_users_table.php
Schema::create('users', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->unsignedInteger('user_parent_id')->nullable();
$table->unsignedInteger('company_id')->nullable();
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
這是公司表遷移,文件名是2018_06_01_080858_create_company_table.php
Schema::create('company', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->unsignedInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
....
$table->timestamps();
});
相反,這是設置外鍵的遷移,文件名是:2018_11_13_111338_alter_foreign_keys.php
Schema::table('users', function($table) {
$table->foreign('user_parent_id')->references('id')->on('users');
$table->foreign('company_id')->references('id')->on('company');
});
當我嘗試運行php artisan:migrate時,我總是會遇到此錯誤:
In Connection.php line 647:
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `users` add constraint `users_company_id_foreign` foreign key (`company_id`) references `company` (`id`))
In PDOStatement.php line 144:
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
In PDOStatement.php line 142:
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
最后,進行遷移,命名為2018_11_13_111338_alter_foreign_keys.php,我為數據庫中的所有其他表依次添加了所有其他外鍵。
任何建議都是值得歡迎的,謝謝。
這是alterForeignTable類的代碼:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AlterForeignTable2 extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('users', function($table) {
$table->foreign('user_parent_id')->references('id')->on('users');
$table->foreign('company_id')->references('id')->on('company');
});
Schema::table('otherstable', function($table) {
$table->foreign('user_id')->references('id')->on('users');
});
}
}
您有兩個模型,並添加了兩個外部ID。 這是許多工作。 您只需要添加帶有company_id和user_id的數據透視表即可
https://laraveldaily.com/pivot-tables-and-many-to-many-relationships/
首先,您必須將user_id字段設為索引:
$table->index('user_id');
之后,您可以創建一個對級聯操作的外鍵:
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
如果要通過新的遷移來做到這一點,則必須首先刪除索引和外鍵,然后從頭開始做所有事情。
在down()函數中,您必須執行此操作,然后在up()中,執行我上面寫的內容:
$table->dropForeign('user_parent_id');
$table->dropIndex('lists_user_id_index');
$table->dropColumn('user_id');
試試這個,希望它能起作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.