簡體   English   中英

Laravel 5.3 遷移:1215 無法添加外鍵約束

[英]Laravel 5.3 Migration: 1215 Cannot add foreign key constraint

我正在使用 Laravel 5.3 並且我正在嘗試創建 FK,但是當我使用 artisan 遷移我的表時,我收到以下錯誤:

  [Illuminate\Database\QueryException]
  SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `topic_video` add constraint `topic_video_vendor_id_foreign` foreign key (`vendor_id`) references `vendors` (`id`))



  [Doctrine\DBAL\Driver\PDOException]
  SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint



  [PDOException]
  SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint

我已經為不同的 laravel 版本在 SOF 上嘗試了多種解決方案,但它們都不起作用。

這是我的 topic_video 表(InnoDB)

在此處輸入圖像描述

這是一個古老而大的項目,因為我沒有為它遷移,只有對於我們有遷移的新表。 所以我創建了一個供應商(MyISAM)

Schema::create('vendors', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('channel_url');
            $table->timestamps();
        });

然后我將上述遷移的 FK 添加到 topic_video 表中。

Schema::table('topic_video', function (Blueprint $table) {
            $table->integer('vendor_id')->unsigned()->nullable();
            $table->foreign('vendor_id')->references('id')->on('vendors');
        });

我試過沒有 unsigned(),沒有 nullable() 但仍然沒有工作! 任何幫助,將不勝感激!

嘗試這個..

public function up()
{
    Schema::create('topic_video', function (Blueprint $table) {
        $table->integer('vendor_id')->unsigned()
    });
    Schema::table('topic_video', function($table) {
        $table->foreign('vendor_id')->references('id')->on('vendors');
    });
}

並確保供應商遷移創建在 topic_video 遷移創建之前

我想我找到了問題所在...

如果你真的想為非主鍵創建一個外鍵,它必須是一個對其有唯一約束的列。

所以你必須在

$table->integer('vendor_id')->unsigned()->nullable()->unique();

請參見:

https://stackoverflow.com/a/18435114/10573560

https://docs.microsoft.com/en-us/previous-versions/sql/sql-server-2008-r2/ms175464(v=sql.105)?redirectedfrom=MSDN

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM