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

希望有人能帮我开始。


当前回答

这么简单!!

如果您第一次创建“priorities”迁移文件,Laravel首先运行“priorities”而“users”表不存在。

它如何向一个不存在的表添加关系!

解决方案:从“优先级”表中取出外键代码。你的迁移文件应该是这样的:

并添加到一个新的迁移文件,这里它的名字是create_prioritiesForeignKey_table,并添加这些代码:

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

其他回答

我们不能添加关系,除非创建了相关的表。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');
    });

如果以上解决方案都不适合新手,检查两个id是否具有相同的类型:都是整数或都是bigInteger,…你可以有这样的东西:

主表(例如用户)

$table->bigIncrements('id');

子表(例如优先级)

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

此查询将失败,因为用户。id是一个大整数,而优先级。user_id是一个整数。

在这种情况下,正确的查询如下:

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

另一个原因可能是DB引擎类型。Laravel默认使用MyISAM引擎。所以如果你需要强制外键引用检查,你应该使用InnoDB作为你的引擎。

这个设置在config/database.php文件中。将引擎改为'engine' => 'InnoDB'

另外,如果您试图对现有表执行此操作,请使用

DB::statement("ALTER TABLE ' {$tableName} ' ENGINE = 'InnoDB'");

对我来说,问题是旧表使用MyISAM而不是InnoDB。这就解决了问题

    $tables = [
        'table_1',
        'table_2'
    ];

    foreach ($tables as $table) {
        \DB::statement('ALTER TABLE ' . $table . ' ENGINE = InnoDB');
    }

我注意到的一件事是,如果表使用不同的引擎比外键约束不起作用。

例如,如果一个表使用:

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