尝试使用Laravel迁移添加外键约束时出错

时间:2018-05-26 12:44:07

标签: php laravel-5

我正在尝试找出外键,但在向我的代码添加$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');后尝试迁移时,我收到此错误:

"SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL
  : alter table `images` add constraint `images_user_id_foreign` foreign key
  (`user_id`) references `users` (`id`) on delete cascade)
"

用户迁移:

Schema::create('users', function (Blueprint $table) {
                $table->increments('id');
                $table->string('first_name');
                $table->string('last_name');
                $table->string('username');
                $table->string('password');
                $table->string('email');
                $table->string('profile_picture')->nullable()->default('image');
                $table->timestamps();
                $table->rememberToken();
                $table->engine = 'InnoDB';
            });

图片迁移:

Schema::create('images', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('description')->nullable()->default(null);
            $table->integer('user_id');
            $table->foreign('user_id')
                  ->references('id')
                  ->on('users')
                  ->onDelete('cascade');
            $table->string('file_name');
            $table->string('upvotes')->default(0);
            $table->string('downvotes')->default(0);
            $table->string('views')->default(0);
            $table->timestamps();
            $table->engine = 'InnoDB';
        });

1 个答案:

答案 0 :(得分:1)

这可能是因为你正在使用不同的数据类型,尝试使数据类型相同,它应该工作。 Int - bigInt或string Int,请检查。

还分两步添加, 并且使它无符号也很好。

否则一定是打字错误。