【问题标题】:errno: 150 "Foreign key constraint is incorrectly formed" how can i fix this?errno: 150“外键约束格式不正确”我该如何解决这个问题?
【发布时间】:2020-01-14 12:11:48
【问题描述】:

我一直在尝试不同的方法,但我无法消除错误。所以我的问题是:其他人可以看到错误吗?

这是我的代码:

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


public function up()
{
    Schema::create('places', function (Blueprint $table) {
        $table->bigIncrements('id')->unique();
        $table->string('location_name');
        $table->string('village');
        $table->string('street');
        $table->integer('number')->unsigned();
    });
}

public function up()
{
    Schema::create('planning', function (Blueprint $table) {
        $table->bigIncrements('id')->unique();
        $table->unsignedInteger('places_id');
        $table->time('van');
        $table->time('tot');
        $table->date('dag');
        $table->timestamps();
        $table->unsignedInteger('created_by');

        $table->foreign('places_id')
            ->references('id')
            ->on('places')
            ->onDelete('cascade');

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

}

PDOException::("SQLSTATE[HY000]: 一般错误:1005 无法创建 table `foodtruck`.`#sql-3be8_b8` (errno: 150 "外键约束 格式不正确")")

我希望此错误消息能够以我可以正常使用的方式修复我的命令行和迁移文件:)

【问题讨论】:

  • 你在哪里创建表foodtruck
  • 查看this question,它的答案之一可能会对您有所帮助。

标签: php mysql laravel migration


【解决方案1】:

因为places_idcreated_by被定义为bigIncrements,所以不能将它们的外键定义为unsignedInteger,它需要是对应的数据类型,根据documentation是:

自动递增 UNSIGNED BIGINT(主键)等效列。

相当于unsignedBigInteger

改变,

$table->unsignedInteger('places_id');
$table->unsignedInteger('created_by');

到,

$table->unsignedBigInteger('places_id');
$table->unsignedBigInteger('created_by');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-19
    • 2018-03-02
    • 2020-07-07
    • 1970-01-01
    • 2017-04-13
    • 2018-09-04
    • 2019-09-17
    • 2020-12-16
    相关资源
    最近更新 更多