首页 > 解决方案 > Laravel 一般错误:1005 无法创建表

问题描述

我在执行 php artisan 迁移时收到此错误。我的迁移文件有问题吗?

Illuminate\Database\QueryException : SQLSTATE[HY000]: General error: 1005 Can't create table testblog_posts(errno: 150 "Foreign key constraint is wrongly forms") (SQL: alter table blog_postsadd constraint blog_pos ts_user_id_foreignforeign key ( user_id) 引用users( id))

博客帖子

        $table->increments('id');
        $table->integer('cаtegory_id')->unsigned();
        $table->integer('user_id')->unsigned();
        $table->string('slug')->unique();
        $table->string('title');
        $table->text('excerpt')->nullable(); դաշտ չի
        $table->text('content_raw');
        $table->text('content_html');
        $table->boolean('is_published')->default(false);
        $table->timestamp('published_at')->nullable();
        $table->timestamps();
        $table->softDeletes(); 
        $table->foreign('user_id')->references('id')->on('users');
        $table->foreign('cаtegory_id')->references('id')->on('blog_categories');
        $table->index('is_published');

博客类别

    $table->increments('id');
    $table->integer('parent_id')->unsigned()->default(0); 
    $table->string('slug')->unique();
    $table->string('title');
    $table->text('description')->unllable(); 
    $table->timestamps(); 
    $table->softDeletes();

用户

        $table->bigIncrements('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->timestamp('email_verified_at')->nullable();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();

标签: phplaravelforeign-keysmigrationlaravel-migrations

解决方案


您需要将用户表中的列类型和格式匹配到 FK。但是您首先需要在blog_posts表上实际创建列,从中绘制 FK 以完全匹配您在 users 表上的内容

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

是 FK 指令,但在此之前,您需要添加实际列以匹配用户表。Nullable 是可选的,具体取决于您要如何进行:

$table->bigInteger('user_id')->unsigned()->nullable();

推荐阅读