一般错误:1215无法添加外键约束,Laravel 5和MySQL

Tyl*_*den 0 php mysql migration laravel

在一个空白的Laravel项目中,我想在用户问题之间创建外键约束,其中users表将包含内置Laravel User,但Question它将是一个自定义模型。

运行后, php artisan migrate将发生以下错误:

   Illuminate\Database\QueryException  : SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `questions` add constraint `questions_user_id_foreign` foreign key (`user_id`) references `users` (`id`) on delete cascade)
  at /home/artur/Exposit/EDU/PHP/lara/vendor/laravel/framework/src/Illuminate/Database/Connection.php:664
    660|         // If an exception occurs when attempting to run a query, we'll format the error
    661|         // message to include the bindings with SQL, which will make this exception a
    662|         // lot more helpful to the developer instead of just the database's errors.
    663|         catch (Exception $e) {
  > 664|             throw new QueryException(
    665|                 $query, $this->prepareBindings($bindings), $e
    666|             );
    667|         }
    668| 
Run Code Online (Sandbox Code Playgroud)

这是laravel生成的create_users_table迁移:

 Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
Run Code Online (Sandbox Code Playgroud)

这是我的迁移:

Schema::create('questions', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('title');
            $table->string('slug')->unique();
            $table->text('body');
            $table->unsignedInteger('views')->default(0);
            $table->unsignedInteger('answers')->default(0);
            $table->integer('votes')->default(0);
            $table->unsignedInteger('best_answer_id')->nullable();
            $table->unsignedInteger('user_id');
            $table->timestamps();
        });

        Schema::table('questions', function (Blueprint $table) {
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        });
Run Code Online (Sandbox Code Playgroud)

我试图将问题表的创建和外键约束的更改分为两个迁移,但是却出现了相同的错误。请注意,关于stackoverflow的所有相关答案都对我没有帮助。

San*_*aur 7

Laravel 5.8添加了bigIncrements作为默认值

因此,外键字段类型不匹配。您在用户表中看到bigIncrements(id),在问题表中看到无符号整数(user_id)。

怎么修

  • 可以将原始迁移从bigIncrements()更改为justinstance
    ()
  • 或者在外键列中执行unsignedBigInteger()而不是unsignedInteger()。