Möglichkeiten zur Vermeidung von Fehlern beim Hinzufügen von Fremdschlüsseln in Laravel
P粉311617763
P粉311617763 2023-09-09 00:27:09
0
1
513

Kannst du mir helfen? Ich möchte dabei sein 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")")

Das ist meine postsUhr

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

Das ist meine categoriesUhr

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

P粉311617763
P粉311617763

Antworte allen(1)
P粉225961749

this is my approach:

$table->unsignedBigInteger('category_id');
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade')->onUpdate('cascade');
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage