这是每次显示的错误。
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()用户表
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();
});
}员额表
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迁移命令创建表。
发布于 2022-04-06 14:08:41
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');
});发布于 2022-11-27 07:35:07
我也犯了这个错误。当外键类型与其引用类型不匹配时,此错误将处理。例如,如果外键类型为(int),但引用键类型是(biginteger),则此错误将处理。
https://stackoverflow.com/questions/71767744
复制相似问题