Ways to avoid errors when adding foreign keys in Laravel
P粉311617763
P粉311617763 2023-09-09 00:27:09
0
1
352

Can you help me? I want to add a foreign key to the posts table that has a reference in the categories table. But when I enter the command php artisan migrate:fresh, it always fails. The error message I got is this PDOException::("SQLSTATE[HY000]: General error: 1005 Can't create table 'handconsulting'.'posts' (errno: 150 "Foreignkey constraint is incorrectly formed")" )

This is my postsTable

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

This is my categoriesTable

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!