laravel 数据库状态[HY000]:一般错误:1005无法创建表格(错误号:150 "外键约束的格式不正确")

tf7tbtn2  于 2023-01-21  发布在  其他
关注(0)|答案(3)|浏览(117)

我想在模型PostCategory之间创建一个一对多的关系,但是我得到
SQLSTATE[HY000]: General error: 1005 Can't create tableschool.posts(errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter tablepostsadd constraintposts_category_id_foreignforeign key (category_id) referencescategories(id) on delete cascade)

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);
    }
}
z3yyvxxp

z3yyvxxp1#

您的foreign_key字段和您的id应该是相同的类型,例如,如果categories.idbigIncrements,那么您的Post table中的foreign_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();
});

注意:应确保在运行分类表迁移之前运行过帐表迁移。

bfrts1fy

bfrts1fy2#

$table->id();创建一个unSignedBigInteger***(无符号位)***。
$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");
xeufq47z

xeufq47z3#

从表底部删除外键约束
请参见屏幕截图here

相关问题