在MySQL中错误地形成了外键约束:Laravel迁移

问题描述 投票:0回答:1

我的迁移是

Schema::create('user_details', function (Blueprint $table) {
    $table->Increments('id')->unique();
    $table->text('detail');
    $table->text('value');
    $table->integer('user_id');
    $table->timestamps();

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

Schema::create('users', function (Blueprint $table) {
    $table->Increments('id')->unique();
    $table->integer('user_detail_id');
    $table->integer('user_setting_id');
    $table->integer('company_id');
    $table->mediumText('role');
    $table->mediumText('email')->unique();
    $table->mediumText('password');
    $table->timestamps();
});

[当我尝试迁移时,出现此错误消息:

errno:150“外键约束格式不正确”(SQL:alter表user_details添加约束user_details_user_id_foreign外键(user_id)引用usersid))

为什么会这样?

php mysql laravel database-migration
1个回答
0
投票

您需要为表设置InnoDB存储引擎。您可以在模式构建器中进行此操作:$table->engine = 'InnoDB';或在config/database.php文件(connections => mysql => engine)中:将'engine' => null,更改为'engine' => 'InnoDB',

第二,定义为$table->increments('id');的主键是自动递增的UNSIGNED INTEGER。并且您的外键应该未签名。了解有关creating columns的更多信息。

Schema::create('user_details', function (Blueprint $table) {
    $table->engine = 'InnoDB';

    $table->increments('id');
    $table->text('detail');
    $table->text('value');
    $table->unsignedInteger('user_id');
    $table->timestamps();

    $table->foreign('user_id')->references('id')->on('users');
});
Schema::create('users', function (Blueprint $table) {
    $table->engine = 'InnoDB';

    $table->increments('id');
    $table->integer('user_detail_id');
    $table->integer('user_setting_id');
    $table->integer('company_id');
    $table->mediumText('role');
    $table->mediumText('email')->unique();
    $table->mediumText('password');
    $table->timestamps();
});
© www.soinside.com 2019 - 2024. All rights reserved.