2017-02-23 31 views
0

添加外鍵在laravel遷移文件我有以下代碼:無法在Laravel

Schema::table('stripe_customers', function (Blueprint $table) { 
      $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); 
    }); 

「USER_ID」是表「stripe_customers」現有的無符號整數列。

'id'是'users'中的主鍵列。

然而,當我運行遷移命令我收到以下錯誤信息:

[Illuminate\Database\QueryException]                  
    SQLSTATE[HY000]: General error: 1005 Can't create table 'thedealerapp.#sql-47a_78859' (errno: 150) (SQL: 
    alter table `stripe_customers` add constraint stripe_customers_user_id_foreign foreign key (`user_id`) 
    references `users` (`id`))                     

    [PDOException]                      
    SQLSTATE[HY000]: General error: 1005 Can't create table 'thedealerapp.#sql-47a_78859' (errno: 150) 

這究竟是爲什麼?

+0

如果您刪除該調用並嘗試直接將其添加到數據庫,會發生什麼情況? – cwallenpoole

+1

由於列類型或表格整理不匹配,通常會發生150錯誤。 – Robert

+0

[MySQL外鍵錯誤1005 errno 150]的可能重複(http://stackoverflow.com/questions/4063141/mysql-foreign-key-error-1005-errno-150) – cwallenpoole

回答

1

因此,導致無法創建外鍵的原因有幾種。

  • usersid索引? MySQL需要兩個表上的索引來創建一個外鍵。而stripe_customersuser_id是隱式創建的,請確保usersid
  • 您是否有stripe_customers的內容可能無法通過外鍵檢查?這會在創建外鍵時導致錯誤。
  • 您是否確認兩個表的列類型相同? MySQL會要求兩者都是相同的
  • 你能確認兩個表都在同一個模式嗎?如果其中一個表格以某種方式在不同的DB中,那麼MySQL需要明確引用該DB。
+0

問題是一列沒有簽名,而另一個沒有簽名。感謝您的幫助 –