繁体   English   中英

SQLSTATE[HY000]: 一般错误: 1005 Can't create table `school`.`posts` (errno: 150 "Foreign key constraint is wrongly forms")

[英]SQLSTATE[HY000]: General error: 1005 Can't create table `school`.`posts` (errno: 150 "Foreign key constraint is incorrectly formed")

在一切之前,我尝试了许多网站和论坛来解决这个问题,直到这些帖子与 StackOverflow 中的这个问题相关,但我无法解决问题。 我想在帖子和类别model 之间创建一对多的关系,但我得到了那个错误代码。

SQLSTATE[HY000]: 一般错误: 1005 Can't create table school posts (errno:150“外键约束不正确”)(SQL:alter table posts添加约束posts_category_id_foreign外键( category_id )在删除级联时引用categoriesid ))

        Schema::create('categories', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('slug');
            $table->timestamps();
        });
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->integer('category_id')->unsigned();
            $table->foreign('category_id')->nullable()->references('id')->on('categories');
            $table->string('title')->nullable();
            $table->timestamps();
        });
    }


class Category extends Model
{
    use HasFactory;

    protected $table = 'categories';

    protected $guarded = [];


    public function posts(){
        return $this->hasMany(Post::class);
    }
}
class Post extends Model
{
    use HasFactory;

    protected $guarded = [];

    public function category(){
        return $this->belongsTo(Category::class);
    }


}

请帮助我,感谢您的帮助。

你的foreign_key字段和你的id应该是相同的类型,例如,如果categories.idbigIncrements ,你Post tableforeign_key也应该是bigInteger

类别表

Schema::create('categories', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->string('name');
    $table->string('slug');
    $table->timestamps();
});

发布表

Schema::create('posts', function (Blueprint $table) {
    $table->id();
    $table->bigInteger('category_id')->unsigned()->nullable();
    $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
    $table->string('title')->nullable();
    $table->timestamps();
});

注意:您应该确保您的类别表迁移在发布表迁移之前运行。

$table->id(); 创建一个unSignedBigInteger (UNSIGNED BIGINT)

$table->integer('category_id')->unsigned(); 创建一个unSignedInteger (无符号整数)

使固定

// Instead of:
$table->integer('category_id')->unsigned(); ❌

// Use this:
$table->unsignedBigInteger("category_id")->nullable(); ✅

$table->foreign("category_id")
                ->references("id")
                ->on("categories")
                ->onDelete("set null");

从表格底部删除外键约束

在此处查看屏幕截图

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM