如何在 laravel 中添加外键而不出错?

发布于 2025-01-12 02:42:08 字数 1256 浏览 2 评论 0原文

你们能帮我吗?我想在 posts 表中添加一个外键,该外键在 categories 表中具有引用。但是当我输入命令 php artisan migrate:fresh 时它总是失败。我得到的错误是这样的 PDOException::("SQLSTATE[HY000]: General error: 1005 Can't create table 'handconsulting'.'posts' (errno: 150 "Foreignkey constrained is invalid 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();
        });

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

this is my posts table

 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 categories table

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

獨角戲 2025-01-19 02:42:08

这是我的方法:

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

this is my approach:

$table->unsignedBigInteger('category_id');
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade')->onUpdate('cascade');
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文