web-dev-qa-db-ja.com

移行:laravelに外部キー制約を追加できない

Laravelに外部キーを作成しようとしていますが、artisanを使用してテーブルを移行すると、次のエラーが発生します。

[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL
: alter table `priorities` add constraint priorities_user_id_foreign foreign 
key (`user_id`) references `users` (`id`))     

私の移行コードはそうです:

優先順位移行ファイル

public function up()
{
    //
    Schema::create('priorities', function($table) {
        $table->increments('id', true);
        $table->integer('user_id');
        $table->foreign('user_id')->references('id')->on('users');
        $table->string('priority_name');
        $table->smallInteger('rank');
        $table->text('class');
        $table->timestamps('timecreated');
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    //
    Schema::drop('priorities');
}

ユーザー移行ファイル

public function up()
{
    //
    Schema::table('users', function($table)
    {
    $table->create();
    $table->increments('id');
    $table->string('email');
    $table->string('first_name');
    $table->string('password');
    $table->string('email_code');
    $table->string('time_created');
    $table->string('ip');
    $table->string('confirmed');
    $table->string('user_role');
    $table->string('salt');
    $table->string('last_login');

    $table->timestamps();
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    //
        Schemea::drop('users');
}

私が作成しなければならないテーブルがたくさんあるので、私が間違ったことについてのどんな考えでも、私は今すぐこれを手に入れたいです。ユーザー、クライアント、プロジェクト、タスク、ステータス、優先度、タイプ、チーム。理想的には、このデータを外部キー、つまりclients_projectproject_tasksなどで保持するテーブルを作成したいです。

誰かが私が始めるのを手伝ってくれることを願っています。

前もって感謝します。

136
001221

2つのステップでそれを追加してください、そしてそれもそれを未署名にすることは良いことです:

public function up()
{
    Schema::create('priorities', function($table) {
        $table->increments('id', true);
        $table->integer('user_id')->unsigned();
        $table->string('priority_name');
        $table->smallInteger('rank');
        $table->text('class');
        $table->timestamps('timecreated');
    });

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

}
289

質問はすでに答えていますが、これが他の人に役立つことを願っています。

キーが元のテーブルの主キーとして存在する前に、最初に外部キーを含む移行テーブルを作成したため、このエラーが発生しました。マイグレーションは、migrate:makeの実行後に生成されたファイル名で示されているとおりに、作成された順序で実行されます。例えば。 2014_05_10_165709_create_student_table.php

解決策は、ここで推奨されているように、外部キーを使用してファイルの名前を主キーを使用しているファイルよりも早い名前に変更することでした。 = 10246

私も$table->engine = 'InnoDB';を追加しなければならなかったと思います

94
haakym

私の場合、問題はメインテーブルにすでにレコードがあり、新しいカラムをNULLにしないように強制していたことです。そのため、新しいカラムに - > nullable()を追加するとうまくいきます。質問の例では、次のようになります。

$table->integer('user_id')->unsigned()->nullable();

または

$table->unsignedInteger('user_id')->nullable();

これが誰かに役立つことを願っています!

42
AdrianCR

私の場合、問題はusersテーブルの自動生成された移行が

...
$table->bigIncrements('id');
...

だから私は列の種類を変更する必要がありました


$table->bigInteger('id');

外部キーによる移行を機能させるため。

これはlaravel 5.8.2と一緒に

16
Daniele

私の場合は、移行のタイミングに問題がありましたが、移行を作成する際に最初に基本移行よりも子移行を作成していました。あなたが最初にあなたの外部キーを持っている基本マイグレーションを作成するならば、子テーブルを探すでしょう、そして、例外を投げるテーブルがないでしょう。

さらにもっと:

移行を作成すると、その先頭にタイムスタンプが付きます。マイグレーションを作成したとしましょうcatだから2015_08_19_075954_the_cats_time.phpのようになり、それはこのコードを持っています

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class TheCatsTime extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('cat', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');  
            $table->date('date_of_birth');
            $table->integer('breed_id')->unsigned()->nullable(); 
        });

        Schema::table('cat', function($table) {
        $table->foreign('breed_id')->references('id')->on('breed');
      });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('cat');
    }
}

そして、ベーステーブルを作成した後に、別の移行を作成しますbreedこれは子テーブルで、それはそれ自身の作成時間と日付スタンプを持ちます。コードは次のようになります。

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class BreedTime extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('breed', function (Blueprint $table) {
             $table->increments('id');    
             $table->string('name');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('breed');
    }
}

どちらの表も正しいようですが、実行するとphp artisan migrateです。最初にこの移行を作成したため、移行によってデータベースに基本テーブルが作成され、その中に子テーブルを検索する外部キー制約があり、子テーブルが存在しないため、例外が発生します。例外..

だから:

最初に子テーブルの移行を作成します。

子の移行が作成された後に、ベーステーブルの移行を作成します。

php職人が移行します。

うまくいきました

14
Vicky

ラレベル^ 5.8

Laravel 5.8以降 、デフォルトでは、移行スタブはID列に対してbigIncrementsメソッドを使用します。以前は、ID列はincrementsメソッドを使用して作成されていました。

これはプロジェクト内の既存のコードには影響しません。ただし、外部キーカラムは同じ型である必要があります。したがって、incrementsメソッドを使用して作成された列は、bigIncrementsメソッドを使用して作成された列を参照できません

出典: 移住と大規模増加


単純なロールベースのアプリケーションを作成していて、PIVOTuser_idを参照する必要があるとしましょう。 )テーブル "role_user"

2019_05_05_112458_create_users_table.php

// ...

public function up()
{
    Schema::create('users', function (Blueprint $table) {

        $table->bigIncrements('id');

        $table->string('full_name');
        $table->string('email');
        $table->timestamps();
    });
}

2019_05_05_120634_create_role_user_pivot_table.php

// ...

public function up()
{
    Schema::create('role_user', function (Blueprint $table) {

        // this line throw QueryException "SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint..."
        // $table->integer('user_id')->unsigned()->index();

        $table->bigInteger('user_id')->unsigned()->index(); // this is working
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    });
}

ご覧のとおり、アップグレードノートに記載されているように、外部キー列は同じ型である必要があるため、コメント行はクエリ例外をスローします。そのため、role_userのフォーリングキー(この例ではuser_id)をbigIntegerに変更する必要があります。 )テーブルまたはusersテーブルでbigIncrementsメソッドをincrementsメソッドに変更し、ピボット内のコメント行を使用するテーブル、それはあなた次第です。


私はあなたにこの問題を明確にすることができたと思います。

12
chebaby

私の場合は、テーブルのユーザーが最初に作成されるように、移行が手動で実行される順序を変更するだけです。

フォルダdatabase/migrations/migrationのファイル名は次のフォーマットになります。year_month_day_hhmmss_create_XXXX_table.php

ユーザー優先順位テーブルの作成日がユーザー日付より後に設定されるように、ユーザーファイルの名前を変更するだけです(1秒後でも十分です)。

12
ldt

私は同じ問題を抱えていましたLaravel 5.8。 laravelドキュメントを詳しく見た後に、ここでも Migrations&bigIncrements 。私がそれを解決した方法は主キーを追加することです"$ table-> bigIncrements( 'id')"テーブルに関連するすべての単一のテーブルに"users"そしてその関連付け、私の場合は表"role"。最後に、ロールをユーザーに関連付けるための"$ table-> unsignedBigInteger"、つまりtable "role_user"を持っていました。

1. Users table

    Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });

2. Roles Table
    Schema::create('roles', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name')->unique();
        $table->string('display_name')->nullable();
        $table->string('description')->nullable();
        $table->timestamps();
    });

3. Table role_user
Schema::create('role_user', function (Blueprint $table) {
            $table->unsignedBigInteger('user_id');
            $table->unsignedBigInteger('role_id');
            $table->foreign('user_id')->references('id')->on('users')
                ->onUpdate('cascade')->onDelete('cascade');
            $table->foreign('role_id')->references('id')->on('roles')
                ->onUpdate('cascade')->onDelete('cascade');
            $table->primary(['user_id', 'role_id']);
        });
6
Capfer

関連テーブルが作成されない限り、リレーションを追加することはできません。 Laravel移行ファイルの日付順に移行を実行します。そのため、2番目の移行ファイルに存在するテーブルとの関係を作成したい場合は失敗します。

私は同じ問題に直面しました、それで私はついにすべての関係を指定するためにもう一つの移行ファイルを作成しました。

Schema::table('properties', function(Blueprint $table) {
        $table->foreign('user')->references('id')->on('users')->onDelete('cascade');
        $table->foreign('area')->references('id')->on('areas')->onDelete('cascade');
        $table->foreign('city')->references('id')->on('cities')->onDelete('cascade');
        $table->foreign('type')->references('id')->on('property_types')->onDelete('cascade');
    });

    Schema::table('areas', function(Blueprint $table) {
        $table->foreign('city_id')->references('id')->on('cities')->onDelete('cascade');
    });
5
pavan kumar

Laravel 5.3を使用しても同じ問題が発生しました。

解決策は、integer( 'name') - > unsigned()の代わりにunsignedIntegerを使用することでした。

だからこれはうまくいったものです

$table->unsignedInt('column_name');
$table->foreign('column_name')->references('id')->on('table_name');

これがうまくいった理由は、integer( 'name') - > unsignedを使うとき、テーブルに作成されたカラムの長さは11ですが、unsigedInteger( 'を使うとき)です。 name ')列の長さは10です。

長さ10は、Laravelを使用するときの主キーの長さなので、列の長さは一致します。

4
Radu Diță

Laravelに外部キー制約を追加するためには、次のものが役に立ちました。

  1. 次のようにして列を外部キーにします。

    $ table-> integer( 'column_name') - > unsigned();
  2. (1)の直後に拘束線を追加する。

    $ table-> integer( 'column_name') - > unsigned(); 
     $ table-> foreign( 'column_name') - > references( 'pk_of_other_table') - > on( 'other_table');
4
bmnepali

注意してください:Laravelが以下を使ってテーブルを設定するとき

$table->increments('id');

これはほとんどの移行で標準的ですが、これは符号なし整数フィールドを設定します。したがって、別のテーブルからこのフィールドへの外部参照を作成するときは、参照テーブルで、フィールドをUnsignedIntegerに設定し、UnsignedBigIntegerフィールドには設定しないでください。

たとえば、移行ファイル2018_12_12_123456_create_users_table.phpでは、次のようになります。

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

次に、マイグレーションファイル2018_12_12_18000000_create_permissions_table.phpに、外部参照をユーザーに戻します。

Schema::create('permissions', function (Blueprint $table){
    $table->increments('id');
    $table->UnsignedInteger('user_id'); // UnsignedInteger = "increments" in users table
    $table->boolean('admin');
    $table->boolean('enabled');
    $table->timestamps();

    // set up relationship
    $table->foreign('user_id')->reference('id')->on('users')->onDelete('cascade');
}
3
bnoeafk

私はそれが古い質問であることを知っていますが、あなたが参照を使って作業しているかどうかは適切な支援エンジンが定義されていることを確認してください。両方のテーブルにinnodbエンジンを設定し、参照列に同じデータ型を設定します。

$table->engine = 'InnoDB';
3
di3

最初の質問から数年後のlaravel 5.1を使用して、ここに集中してみましたが、移行はすべて同じ日付コードでコンピューターによって生成されたのと同じエラーが発生しました。私はすべての提案された解決策を経て、それからエラーの原因を見つけるためにリファクタリングしました。

以下の記事を読んで、そしてこれらの記事を読んで、私はあなたが別のスキーマ呼び出しを追加する必要がないことを除いて、正しい答えはVickiesの答えに似ていると思います。あなたはテーブルをInnodbに設定する必要はありません、私はlaravelが今それをしていると仮定しています。

マイグレーションは単に正確にタイミングを合わせる必要があります。つまり、外部キーが必要なテーブルのファイル名の日付コードを(後で)変更します。あるいは、またはさらに、外部キーを必要としないテーブルの日付コードを下げます。

日付コードを変更することの利点は、移行コードが読みやすく維持しやすいことです。

これまでのところ、私のコードは、タイムコードを外部キーを必要とするマイグレーションをプッシュバックするように調整することによって機能しています。

しかし、私は何百ものテーブルを持っているので、最後に外部キーだけのための最後のテーブルを一つ持っています。物事を流すためだけに。私はそれらを正しいファイルに入れて、私がそれらをテストするときに日付コードを修正すると仮定しています。

例:ファイル2016_01_18_999999_create_product_options_table。これにはproductsテーブルを作成する必要があります。ファイル名を見てください。

 public function up()
{
    Schema::create('product_options', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('product_attribute_id')->unsigned()->index();
        $table->integer('product_id')->unsigned()->index();
        $table->string('value', 40)->default('');
        $table->timestamps();
        //$table->foreign('product_id')->references('id')->on('products');
        $table->foreign('product_attribute_id')->references('id')->on('product_attributes');
        $table->foreign('product_id')->references('id')->on('products');


    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::drop('product_options');
}

商品表:これは最初に移行する必要があります。 2015_01_18_000000_create_products_table

public function up()
{
    Schema::create('products', function (Blueprint $table) {
        $table->increments('id');

        $table->string('style_number', 64)->default('');
        $table->string('title')->default('');
        $table->text('overview')->nullable();
        $table->text('description')->nullable();


        $table->timestamps();
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::drop('products');
}

そして最後に最後に、私が9999_99_99_999999_create_foreign_keys.phpと名付けたモデルのテストを書くときに問題を解決するために一時的に使っているファイルをリファクタリングします。これらのキーは私が引き抜いたときにコメントされていますが、あなたはポイントを得ます。

    public function up()
    {
//        Schema::table('product_skus', function ($table) {
//            $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
//    });

    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
//        Schema::table('product_skus', function ($table)
//        {
//            $table->dropForeign('product_skus_product_id_foreign');
//        });
2
Iannazzi

このエラーは、私が作成しようとしていたテーブルがInnoDBである間、それを関連付けようとしていた外部テーブルがMyISAMテーブルであったために発生しました。

2
bagnap

あなたのフォーリングコラムがフォーリングキーコラムの広い範囲を超えていることを確認してください

私はあなたのフォーリンキー(2番目のテーブルにある)があなたのポンター主キーと同じタイプでなければならないことを意味します(最初のテーブルにある)

あなたのポインタの主キーはunsignedメソッドを追加する必要があります、私に見せてください:

最初の移行テーブルで

$table->increments('column_name'); //is INTEGER and UNSIGNED

2番目の移行テーブルで

$table->integer('column_forein_name')->unsigned(); //this must be INTEGER and UNSIGNED
$table->foreign('column_forein_name')->references('column_name')->on('first_table_name');

違いを見るための別の例

最初の移行テーブルで

$table->mediumIncrements('column_name'); //is MEDIUM-INTEGER and UNSIGNED

2番目の移行テーブルで

$table->mediumInteger('column_forein_name')->unsigned(); //this must be MEDIUM-INTEGER and UNSIGNED
$table->foreign('column_forein_name')->references('column_name')->on('first_table_name');

MySQLの数値型の表の範囲を参照

2
Rubén Ruíz

レベル5.8では、users_tableは主キーにbigIncrements('id')データ型を使用します。そのため、外部キー制約を参照したい場合は、user_id列をunsignedBigInteger('user_id')型にする必要があります。

1
Dhara Talaviya

laravel 5.8でこの問題が発生し、user_idを追加する場所にこのコードを追加するとうまくいきました。

$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

その後、$ php artisan migrate:freshを実行しました

1
Slycreator

私は頭がおかしくなりました、私はただタイプミスがありました:

unsinged()ではなくunsigned()

1
doncadavona

私の場合は、文字列user_id列で整数id列を参照していました。私が変更され:

$table->string('user_id')

に:

$table->integer('user_id')->unsigned();

誰かに役立つことを願っています!

1

あなたは直接それが符号なしであるべきではないということを言って整数の列でブール値のパラメータを渡すことができます。 laravel 5.4では、以下のコードが私の問題を解決しました。

        $table->integer('user_id', false, true);

ここで、2番目のパラメータfalseは自動インクリメントしないことを表し、3番目のパラメータtrueは符号なしを表します。外部キー制約を同じ移行に保持することも、分離することもできます。それは両方に働きます。

1

私の場合、私は列を定義するときに->unsigned()に括弧を使うのを忘れていました。

コードが間違っています$table->integer('permission_id')->unsigned;

真のコード:$table->integer('permission_id')->unsigned();

1
Hamidreza

とても簡単 !!!

最初に'priorities'移行ファイルを作成する場合、Laravelは'priorities'テーブルが存在しない間に最初に'users'を実行します。

存在しないテーブルにリレーションを追加する方法.

解決策:pull out外部キーコード'priorities'テーブルから。移行ファイルは次のようになります。

enter image description here

新しい移行ファイルに追加します。ここでは名前はcreate_prioritiesForeignKey_tableで、次のコードを追加します。

public function up()
{        
    Schema::table('priorities', function (Blueprint $table) {          
        $table->foreign('user_id')
              ->references('id')
              ->on('users');                        
    });
}
1
josef

私の場合は、コマンドを実行するまで動作しませんでした

composer dump-autoload

そうすれば、create schemaの中に外部キーを残すことができます。

public function up()
{
    //
     Schema::create('priorities', function($table) {
        $table->increments('id', true);
        $table->integer('user_id');
        $table->foreign('user_id')->references('id')->on('users');
        $table->string('priority_name');
        $table->smallInteger('rank');
        $table->text('class');
        $table->timestamps('timecreated');
    });
 }

 /**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    //
    Schema::drop('priorities');
}
1

上記の解決策のどれもが初心者には機能しない場合、両方のIDが同じタイプであるかどうかを確認します。両方ともintegerであるか、両方ともbigIntegerです。

メインテーブル(ユーザーなど)

$table->bigIncrements('id');

子テーブル(優先度など)

$table->unsignedInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

users.idBIG INTEGERであるのに対し、priorities.user_idINTEGERであるため、このクエリは失敗します

この場合の正しいクエリは次のとおりです。

$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
1
Waiyl Karim

それはまたあなたの創造物移行の順序かもしれません。あなたが最初にpriorityテーブルを作成し、usersテーブルの後に作成した場合、それは間違っているでしょう。初めての移行でusersテーブルを探しています。だから、あなたは上の移行の順序を変更する必要があります

app/database/migrations

ディレクトリ

1
Turan Zamanlı

ここでの回答から抜けていると思うことが1つあります。間違っている場合は訂正してください。ただし、外部キーはピボットテーブルで索引付けする必要があります。少なくともmysqlではそうであるようです。

public function up()
{
    Schema::create('image_post', function (Blueprint $table) {
        $table->engine = 'InnoDB';
        $table->increments('id');
        $table->integer('image_id')->unsigned()->index();
        $table->integer('post_id')->unsigned()->index();
        $table->timestamps();
    });

    Schema::table('image_post', function($table) {
        $table->foreign('image_id')->references('id')->on('image')->onDelete('cascade');
        $table->foreign('post_id')->references('id')->on('post')->onDelete('cascade');
    });

}
0
Ossi

私が気づいたことの一つは、テーブルが外部キーの制約とは異なるエンジンを使用している場合は動作しないということです。

たとえば、あるテーブルで次のように使用されているとします。

$table->engine = 'InnoDB';

そして他の用途

$table->engine = 'MyISAM';

エラーが発生します。

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

これを修正するには、テーブル作成の最後にInnoDBを追加するだけです。

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->unsignedInteger('business_unit_id')->nullable();

        $table->string('name', 100);

        $table->foreign('business_unit_id')
                ->references('id')
                ->on('business_units')
                ->onDelete('cascade');

        $table->timestamps();
        $table->softDeletes();
        $table->engine = 'InnoDB'; # <=== see this line
    });
}
0
erlandmuchasaj

要点は、外部メソッドがALTER_TABLEを使用して既存のフィールドを外部キーにすることです。そのため、外部キーを適用する前にテーブルタイプを定義する必要があります。ただし、別のSchema::呼び出しに含める必要はありません。このように、create内で両方を実行できます。

public function up()
{
    Schema::create('priorities', function($table) {
        $table->increments('id', true);
        $table->integer('user_id')->unsigned();
        $table->foreign('user_id')->references('id')->on('users');
        $table->string('priority_name');
        $table->smallInteger('rank');
        $table->text('class');
        $table->timestamps('timecreated');
    });
}

また、user_idの型は、外部キーと一致するようにunsignedに設定されています。

0
Menasheh

私の場合、参照されたテーブルの作成を担当する移行が正しく実行されなかったため、データベースに外部キーによって参照されるテーブルがありませんでした。

テーブルが存在するかどうかを確認し、存在しない場合は、このテーブルの移行を確認してください。

0
user3458411

私にとっては、私の子テーブルが参照しているテーブルカラムはインデックスされていません。

Schema::create('schools', function (Blueprint $table) {
    $table->integer('dcid')->index()->unque();
    $table->integer('school_number')->index(); // The important thing is that this is indexed
    $table->string('name');
    $table->string('abbreviation');
    $table->integer('high_grade');
    $table->integer('low_grade');
    $table->timestamps();
    $table->primary('dcid');
});

Schema::create('students', function (Blueprint $table) {
      $table->increments('id');
      $table->integer('dcid')->index()->unique()->nullable();
      $table->unsignedInteger('student_number')->nullable();
      $table->integer('schoolid')->nullable();
      $table->foreign('schoolid')->references('school_number')->on('schools')->onDelete('set null');
      // ...
});

ひどい名前を無視してください、それは別のひどく設計されたシステムからのものです。

0
Grant

ピボットテーブルを作成するときにLaravel 5で同じエラーが発生しました。私の場合の問題は、持っていなかったことです。

->onDelete('cascade');

0
user985366

これで私の問題は解決しました

制約が参照するテーブルまたはインデックスはまだ存在しません

@ haakymが言ったようにあなたがしなければならない唯一の事はxxx_xx_xx_xxxxxx_create_users_tableの名前を変更し、xxx_xx_xx_xxxxxx_create_priorities_tableより早い日時を設定することです

myISAMは制約外部キーをサポートしていないため、MySqlを使用している場合は$table->engine = 'InnoDB';を使用することを忘れないでください。

0
AmirRezaM75

テーブルのエンジンとしてInnoDBを使用してデータベースを作成するときにnsigned()ソリューションに追加する。 外部表外部表に対して従属になる表の前に作成されていることを確認してください。

イラスト

ケース1(フレッシュテーブル)

コメント表投稿表(外部表)に依存しているとします。コメントテーブルを作成する前にpost tableを作成する必要があります

ケース2(すでに存在するテーブル)

あなたのコメントテーブルがあなたの投稿テーブルより前に作成されたとします。新しいマイグレーションファイルにpost tableを作成し、作成した新しいマイグレーションファイルにcomment tableの外部キーを追加しますpost tableマイグレーション後作成されました

PS

あなたはlaravelを使っていると思います

0
sagekoda

このように書くべきです

public function up()
{
    Schema::create('transactions', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->float('amount', 11, 2);
        $table->enum('transaction type', ['debit', 'credit']);
        $table->bigInteger('customer_id')->unsigned();      
        $table->timestamps();                 
    });

    Schema::table('transactions', function($table) {
        $table->foreign('customer_id')
              ->references('id')->on('customers')
              ->onDelete('cascade');
    });     
}

外部キーフィールドはnsignedである必要があります。

0
Mahesh Yadav

テーブルの優先順位に外部キーを作成する必要がある場合

$table->integer('user_id')->unsigned();

$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); 

機能させるには、符号なしの列を作成する必要があります。

0
loay mansour

私は思う:参照キーは "index"でなければなりません。例えば、(down)

public function up()
{
    Schema::create('clicks', function (Blueprint $table) {
        $table->increments('id');
        $table->string('viewer_id');
        $table->integer('link_id')->index()->unsigned();
        $table->string('time');
        $table->timestamps();
    });

    Schema::table('clicks', function($table) {
        $table->foreign('link_id')->references('id')->on('links')->onDelete('cascade');
    });


}

がんばろう。

0
user6602005