如何在 laravel 中添加外键而不出错?
你们能帮我吗?我想在 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是我的方法:
this is my approach: