我试图在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_project和project_tasks等。

希望有人能帮我开始。


当前回答

对于我来说,我的子表引用的表列没有被索引。

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');
      // ...
});

忽略这个糟糕的命名,它来自另一个设计糟糕的系统。

其他回答

我认为这里的答案中遗漏了一件事,如果我错了请纠正我,但是外键需要在数据透视表中被索引。至少在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');
    });

}

我们不能添加关系,除非创建了相关的表。Laravel根据迁移文件的日期顺序运行迁移。因此,如果您想要与第二个迁移文件中存在的表创建关系,则会失败。

我也遇到了同样的问题,所以我最后创建了一个迁移文件来指定所有关系。

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');
    });

其要点是,外部方法使用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以匹配外键。

拉拉维尔 ^5.8

从Laravel 5.8开始,迁移存根在ID上使用bigIncrements方法 列。方法创建ID列 增量的方法。 这不会影响项目中的任何现有代码;然而,是 注意外键列必须具有相同的类型。因此,一个 使用increments方法创建的列不能引用列 使用bigIncrements方法创建。 来源:Migrations & bigIncrements


例子

假设您正在构建一个简单的基于角色的应用程序,并且需要在PIVOT表“role_user”中引用user_id。

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'); }); } As you can see, the commented line will throw a query exception, because, as mentioned in the upgrade notes, foreign key columns must be of the same type, therefore you need to either change the foreing key (in this example it's user_id) to bigInteger in role_user table or change bigIncrements method to increments method in users table and use the commented line in the pivot table, it's up to you. I hope i was able to clarify this issue to you.

有时这种错误可能是由于迁移的顺序造成的。

Users和Order是两个表

订单表有用户的外键 (在迁移过程中,如果Order表先迁移,则会导致问题,因为没有用户匹配外键)

解决方案: 只需将您的Order Update表放在用户下面进行更新

例子: 在我的例子中,教育和大学表 教育表

public function up()
{
    Schema::create('doc_education', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('uni_id')->unsigned()->nullable();
        $table->timestamps();
    });
}

在大学里

    Schema::create('doc_universties', function (Blueprint $table) {
        $table->increments('id');
        $table->string('uni_name');
        $table->string('location')->nullable();
        $table->timestamps();

        //
    });



Schema::table('doc_education', function(Blueprint $table) {
        $table->foreign('uni_id')->references('id')
        ->on('doc_universties')->onDelete('cascade');
    });