【问题标题】:Laravel: Cannot migrate. General error: 1005Laravel:无法迁移。一般错误:1005
【发布时间】:2020-01-15 04:35:00
【问题描述】:

我正在关注 Laracasts TDD,但遇到了一个无论我做什么都无法解决的错误。当我尝试迁移时,它向我显示此错误:

Illuminate\Database\QueryException : SQLSTATE[HY000]: 一般错误: 1005 无法创建表birdboard.#sql-14b8_86 (errno: 150 “外键约束的格式不正确”)(SQL:alter table projects 添加约束 projects_owner_id_foreign 外键 (owner_id) 引用users (id))

我知道 Laravel 现在使用 unsignedBigInteger 代替 unsignedInteger 和 bigIncrements 代替 Increments。我已经完成了所有这些。 我也添加到我的 AppServiceProvider.php 中:

use Illuminate\Support\Facades\Schema;
    public function boot()
    {
        Schema::defaultStringLength(191);
    }

应用服务提供商:

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;

class AppServiceProvider extends ServiceProvider
{

    public function register()
    {
        //
    }


    public function boot()
    {
        Schema::defaultStringLength(191);
    }
}

创建项目表

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateProjectsTable extends Migration
{

    public function up()
    {
        Schema::create('projects', function (Blueprint $table) {

            Schema::dropIfExists('projects');
            $table->bigIncrements('id');
            $table->unsignedBigInteger('owner_id');
            $table->string('title');
            $table->text('description');
            $table->timestamps();

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


    public function down()
    {
        Schema::dropIfExists('projects');
    }
}

您能告诉我我的代码有什么问题吗?为什么会出现错误? https://prnt.sc/p5ku4x

【问题讨论】:

  • 从 create Schema::dropIfExists('projects'); 中删除这一行。问题似乎出在鸟板桌而不是这个?
  • 什么版本的 Laravel?
  • idusers 也是bigIncrement 吗?
  • 尝试运行migrate:fresh
  • @DinoNumić birdboard 好像是数据库名,不是表名

标签: php database laravel


【解决方案1】:

我认为您也需要编辑问题并发布您的所有者模型。数据类型可能有所不同。

$table->unsignedBigInteger('owner_id');

验证是否在两个表中使用相同的数据类型,用于外部表中的 owern_id 和主表中的 id

【讨论】:

  • 是的,这是正确的答案,谢谢。好像我在 users 表上使用 Increments id 并在 projects 表上使用 unsignedBigInteger 并且这造成了冲突。
猜你喜欢
  • 2019-11-21
  • 2019-11-14
  • 2020-03-19
  • 2021-09-20
  • 2017-01-31
  • 2021-02-19
  • 2021-03-20
  • 2014-01-26
  • 2016-07-26
相关资源
最近更新 更多