[英]cannot add foreign key constraint Laravel 5.1
我首先創建了沒有外鍵的所有表,然后從第一個表開始為每個表添加了外鍵,出現了這個錯誤:
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL
: alter table `accounts` add constraint accounts_client_id_foreign foreign
key (`client_id`) references `clients` (`id`))
這是我的代碼:
public function up()
{
Schema::create('accounts', function(Blueprint $table)
{
$table->engine = 'InnoDB';
$table->bigInteger('id');
$table->integer('client_id')->unsigned();
$table->foreign('client_id')->references('id')->on('clients');
$table->integer('emp_id')->unsigned();
$table->foreign('emp_id')->references('id')->on('employees');
$table->string('type');
$table->timestamps();
});
}
我試過沒有$ table-> engine ='innoDB'; 但同樣的錯誤
另外,我試圖分離外鍵:
Schema::table('accounts', function($table) {
$table->foreign('client_id')->references('id')->on('clients');
$table->foreign('emp_id')->references('id')->on('employees');
});
我收到此錯誤:
Base table or view already exists: 1050 Table 'accounts' already exists
因此,當我刪除並重新遷移時,我會遇到第一個錯誤
那怎么了?
我也有同樣的錯誤,對我來說感覺像是錯誤。 我所做的是為外鍵創建了不同的遷移。 因此,首先創建帶有字段的表,然后(接下來是日期遷移)添加外鍵。
然后,我回滾所有遷移,並使用php artisan migrate
migration重新運行它們。 它對我有用,我希望它也對您有用。
我預見到您創建了相關表(“ clients”),將主鍵/ id指定為此
$table->bigInteger('id');
要么
$table->integer('id');
在將您的外鍵約束指定為的意義上,這將導致問題
$ table-> integer('client_id')-> unsigned();
而主鍵/ ID沒有分配unsigned()約束。
因此,將相關表的主鍵更改為
$table->bigInteger('id')->unsigned();
要么
$table->integer('id')->unsigned();
而且,如果您將bigInteger用作主鍵,請嘗試使默認鍵也為bigInteger 。 不要忘了同時使用unsigned() (主鍵和外鍵)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.