gorm 自关联 添加数据

自关联结构体定义

type User struct {
    
    
  Id int `gorm:"autoIncrement"`
  Name      string
  FriendId *int
  Friends      []User `gorm:"foreignkey:FriendId ";references:Id`
}

这里表示一个普通的用户(User),可以拥有很多个朋友,朋友和普通用户拥有一样的数据结构。可以理解成一个User表和一个Friends表关联。
gorm:"foreignkey:FriendId ";references:Id:指定Friends表中的Id作为User表中外键。

为什么外键FriendId 的类型要用(*int)?
因为在添加数据时,如:
insert into User(‘name’,‘friend_id’) values(“lisi”,1)
会报错:Cannot add or update a child row: a foreign key constraint fails
原因在于,user表自关联,user的外键friend_id和Friends的主键id相关联,如果Friends的主键id不存在该值,则会报错误。

但是,插入的值若为null,则不会报错,即,
insert into User(‘name’,‘friend_id’) values(“lisi”,null)不会报错

所以如果FriendId的类型为int,插入的默认值为0,而为*int,可以将其赋值为nil,即可插入null。

猜你喜欢

转载自blog.csdn.net/qxjswl/article/details/131379513