【发布时间】:2021-08-31 20:09:41
【问题描述】:
在一切之前,我尝试了许多网站和论坛来解决这个问题,直到这些帖子与 StackOverflow 中的这个问题相关,但我无法解决问题。 我想在 Post 和 Category 模型之间创建 一对多 关系,但我得到了那个错误代码。
SQLSTATE[HY000]: 一般错误: 1005 Can't create table school.posts (errno: 150 "外键约束格式不正确") (SQL: alter table posts add constraint posts_category_id_foreign外键(category_id)在删除级联时引用categories(id)
Schema::create('categories', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('slug');
$table->timestamps();
});
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->integer('category_id')->unsigned();
$table->foreign('category_id')->nullable()->references('id')->on('categories');
$table->string('title')->nullable();
$table->timestamps();
});
}
class Category extends Model
{
use HasFactory;
protected $table = 'categories';
protected $guarded = [];
public function posts(){
return $this->hasMany(Post::class);
}
}
class Post extends Model
{
use HasFactory;
protected $guarded = [];
public function category(){
return $this->belongsTo(Category::class);
}
}
请帮助我,感谢您的帮助。
【问题讨论】:
标签: php mysql laravel eloquent