首页 > 解决方案 > errno: 150“外键约束格式不正确”我该如何解决这个问题?

问题描述

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

这是我的代码:

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 无法创建表`foodtruck`。`#sql-3be8_b8` (errno: 150 "外键约束格式不正确")")

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

标签: phpmysqllaravelmigration

解决方案


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

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

这相当于unsignedBigInteger

改变,

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

到,

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

推荐阅读