首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Laravel迁移错误外键约束的错误形成

Laravel迁移错误外键约束的错误形成
EN

Stack Overflow用户
提问于 2022-04-06 13:33:58
回答 2查看 134关注 0票数 1

这是每次显示的错误。

代码语言:javascript
复制
   Illuminate\Database\QueryException 

  SQLSTATE[HY000]: General error: 1005 Can't create table `codehacking`.`posts` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `posts` add constraint `posts_user_id_foreign` foreign key (`user_id`) references `users` (`id`) on delete cascade)

  1   G:\Laravel\CodeHacking\vendor\laravel\framework\src\Illuminate\Database\Connection.php:501
      PDOException::("SQLSTATE[HY000]: General error: 1005 Can't create table `codehacking`.`posts` (errno: 150 "Foreign key constraint is incorrectly formed"))
  2   G:\Laravel\CodeHacking\vendor\laravel\framework\src\Illuminate\Database\Connection.php:501
      PDOStatement::execute()

用户表

代码语言:javascript
复制
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->integer('role_id')->index()->unsigned()->nullable();
            $table->integer('is_active')->default(0);
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

员额表

代码语言:javascript
复制
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->integer('user_id')->unsigned()->index();
            $table->integer('category_id')->unsigned()->index();
            $table->integer('photo_id')->unsigned()->index();
            $table->string('title');
            $table->string('body');
            $table->timestamps();

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

每当我试图迁移我的表时,我都会出现这个错误。如何解决这个问题?这个代码是基于laravel-9的。每次收到此错误时,我都会尝试使用php aritsan迁移命令创建表。

EN

回答 2

Stack Overflow用户

发布于 2022-04-06 14:08:41

代码语言:javascript
复制
Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('user_id')->nullable();
            $table->integer('category_id')->unsigned()->index();
            $table->integer('photo_id')->unsigned()->index();
            $table->string('title');
            $table->string('body');
            $table->timestamps();

            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        });
票数 1
EN

Stack Overflow用户

发布于 2022-11-27 07:35:07

我也犯了这个错误。当外键类型与其引用类型不匹配时,此错误将处理。例如,如果外键类型为(int),但引用键类型是(biginteger),则此错误将处理。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71767744

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档