首页  >  问答  >  正文

避免在Laravel中添加外键时出现错误的方法

你们能帮我吗?我想在posts表中添加一个在categories表中有引用的外键。但是当我输入命令php artisan migrate:fresh时,它总是失败。我得到的错误信息是这样的PDOException::("SQLSTATE[HY000]: General error: 1005 Can't create table 'handconsulting'.'posts' (errno: 150 "Foreignkey constraint is incorrectly formed")")

这是我的posts

Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->foreignId('category_id')->constrained('categories')->onDelete('cascade')->onUpdate('cascade');
            $table->string('slug')->unique();
            $table->text('excerpt');
            $table->text('body');
            $table->string('iamge')->nullable();
            $table->timestamp('published_at')->nullable();
            $table->timestamps();
        });

这是我的categories

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

P粉311617763P粉311617763407 天前480

全部回复(1)我来回复

  • P粉225961749

    P粉2259617492023-09-09 16:44:04

    这是我的方法:

    雷雷

    回复
    0
  • 取消回复