我想在模型Post
和Category
之间创建一个一对多的关系,但是我得到SQLSTATE[HY000]: General error: 1005 Can't create table
school.
posts(errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table
postsadd constraint
posts_category_id_foreignforeign key (
category_id) references
categories(
id) on delete cascade)
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);
}
}
3条答案
按热度按时间z3yyvxxp1#
您的
foreign_key
字段和您的id
应该是相同的类型,例如,如果categories.id
是bigIncrements
,那么您的Post table
中的foreign_key
也应该是bigInteger
。类别表
员额表
注意:应确保在运行分类表迁移之前运行过帐表迁移。
bfrts1fy2#
$table->id();
创建一个unSignedBigInteger
***(无符号位)***。$table->integer('category_id')->unsigned();
创建一个unSignedInteger
.***(无符号整数)***。修复
xeufq47z3#
从表底部删除外键约束
请参见屏幕截图here