【问题标题】:Foreign key constraint is incorrectly formed in MySQL: Laravel migrationMySQL 中的外键约束形成错误:Laravel 迁移
【发布时间】:2020-04-04 11:09:03
【问题描述】:

我的迁移是

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】:

您需要为您的表设置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();
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-23
    • 2022-11-27
    • 2021-07-27
    • 2021-04-21
    • 1970-01-01
    • 2019-12-24
    • 2020-07-22
    • 2016-03-03
    相关资源
    最近更新 更多