商品分类 gorm使用has many 关联自身的分类ID时报错

来源:1-15 商品分类的新建,删除和更新接口

hwkkevin

2023-01-10 10:36:13

按照老师提供的代码如下

type Category struct {
	ID               int32     `gorm:"primarykey;type:int"` //为什么使用int32,bigint
	CreatedAt        time.Time `gorm:"column:add_time"`
	UpdatedAt        time.Time `gorm:"column:update_time"`
	DeletedAt        gorm.DeletedAt
	IsDeleted        bool
	Name             string `gorm:"type:varchar(20);not null"`
	ParentCategoryID int32
	ParentCategory   *Category
	SubCategory      []*Category `gorm:"foreignKey:ParentCategoryID;references:ID" json:"sub_category"`
	Level            int32       `gorm:"type:int;not null;default:1;comment '分类层级'"`
	IsTab            bool        `gorm:"default:false;not null;comment '是否展示在tab栏'"`
}

创建表结构时正常
进行数据插入时
Error 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (go_gin_activity.categories, CONSTRAINT fk_categories_sub_category FOREIGN KEY (parent_category_id) REFERENCES categories (id))
该问题如何解决

写回答

1回答

bobby

2023-01-10

这里报错是外键的依赖报错,比如某个这个数据的父category不存在,你检查一下这条数据的parent_category_id值是否在数据库中存在

0

0 学习 · 1399 问题

查看课程