搜尋

首頁  >  問答  >  主體

避免在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粉311617763438 天前508

全部回覆(1)我來回復

  • P粉225961749

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

    this is my approach:

    $table->unsignedBigInteger('category_id');
    $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade')->onUpdate('cascade');

    回覆
    0
  • 取消回覆