Laravel迁移"无法添加外键约束"错误与MySQL数据库

Wai*_*ein 0 mysql foreign-keys laravel laravel-migrations

我正在开发一个Laravel应用程序.我正在使用MySQL作为数据库.我创建了一个模型类,并尝试在其上运行迁移.但是,当我运行迁移时,我在添加外键约束时遇到错误.这就是我到目前为止所做的.

首先,我迁移了运行此命令的内置Laravel用户模型.

php artisan migrate
Run Code Online (Sandbox Code Playgroud)

users表是在数据库中创建的.

然后我创建了另一个运行此命令的模型.

php artisan make:model TodoItem -m
Run Code Online (Sandbox Code Playgroud)

然后我将以下代码添加到迁移文件中.

class CreateTodoItemsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('todo_items', function (Blueprint $table) {
            $table->text('about');
            $table->integer('user_id');
            $table->increments('id');
            $table->timestamps();

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

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('todo_items');
    }
}
Run Code Online (Sandbox Code Playgroud)

如上所示,我通过向todo_items表添加外键来构建users表和todo_items表之间的关系.然后,我尝试通过运行此命令来迁移TodoItem模型.

php artisan migrate
Run Code Online (Sandbox Code Playgroud)

当我运行命令时,我收到此错误.

  Illuminate\Database\QueryException  : SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `todo_items` add constraint `todo_items_user_id_foreign` foreign key (`user_id`) references `users` (`id`) on delete cascade)

  at /var/www/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| 

 Exception trace:

  1   PDOException::("SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint")
      /var/www/vendor/laravel/framework/src/Illuminate/Database/Connection.php:458

  2   PDOStatement::execute()
      /var/www/vendor/laravel/framework/src/Illuminate/Database/Connection.php:458

  Please use the argument -v to see more details.
Run Code Online (Sandbox Code Playgroud)

我在之前使用Postgresql的项目中做了同样的事情.我工作得很好.对于这个项目,我正在使用MySQL数据库,现在它给了我上面的错误.

toy*_*oyi 8

这是因为您已添加$table->integer('user_id');到迁移文件中.您必须添加一个unsignedInteger而不是一个integer,因为表的原始idusersunsigned(并且两列必须完全相同).