2 回答

TA贡献1804条经验 获得超8个赞
关系更接近one-to-many或many-to-many有一个父母可以有多个孩子的
由于我们指的是与孩子相同的类型,我们可以按如下方式更新模型:
type AuthItem struct {
ID uint `gorm:"primaryKey; column:id" json:"id"`
Name string `gorm:"primaryKey; not null; type:varchar(64); column:name" json:"name"`
ItemType int64 `gorm:"type:smallint; not null; column:item_type" json:"item_type"`
Description string `gorm:"size:255; column:description" json:"description"`
AuthRelations []AuthItem `gorm:"many2many:auth_relations; foreignKey:ID; joinForeignKey:Parent; References:ID; joinReferences:Child; constraint:OnUpdate:CASCADE,OnDelete:CASCADE"`
}
AuthItem可以插入为
var relation = []AuthItem{
{
ID: 1,
Name: "super",
AuthRelations: []AuthItem{
{ ID: 2, Name: "admin" },
{ ID: 3, Name: "owner" },
},
}, {
ID: 2,
Name: "user",
AuthRelations: []AuthItem{
{ ID: 3, Name: "normal" },
{ ID: 5, Name: "client" },
},
},
}
err = db.Save(&relation).Error
if err != nil {
log.Fatalf("cant insert: %v", err)
}
log.Printf("Relation: %#v\n", &relation)
Self-Referential-Has-Many同样可以在我们不需要第二张表的地方实现,并且可以使用带有一个额外列的同一张表作为参考
type AuthItem struct {
ID uint `gorm:"primaryKey; column:id" json:"id"`
Name string `gorm:"primaryKey; not null; type:varchar(64); column:name" json:"name"`
ItemType int64 `gorm:"type:smallint; not null; column:item_type" json:"item_type"`
Description string `gorm:"size:255; column:description" json:"description"`
Parent *uint `gorm:"column: parent;" json:"parent"`
AuthRelations []AuthItem `gorm:"foreignKey:Parent"; constraint:OnUpdate:CASCADE,OnDelete:CASCADE"`
}
我们可以像以前一样插入记录

TA贡献1789条经验 获得超8个赞
我得出结论,我需要使用 many2many 关系,这里是案例的例子:
type AuthItem struct {
ID uint `gorm:"uniqueIndex;primaryKey;auto_increment" json:"id"`
Name string `gorm:"unique;not null;type:varchar(64);column:name" json:"name"`
ItemType int64 `gorm:"type:smallint;not null;column:item_type" json:"item_type"`
Description string `gorm:"size:255;column:description" json:"description"`
CreatedAt time.Time `gorm:"default:CURRENT_TIMESTAMP" json:"created_at"`
UpdatedAt time.Time `gorm:"default:CURRENT_TIMESTAMP" json:"updated_at"`
DeletedAt time.Time `gorm:"default:null" json:"deleted_at"`
}
type AuthRelations struct {
ID uint `gorm:"uniqueIndex;primaryKey;auto_increment" json:"id"`
Parent []AuthItem `gorm:"many2many:prnt_authitem_parent;References:Name;constraint:OnUpdate:CASCADE,OnDelete:SET NULL;" json:"parent"`
Child []AuthItem `gorm:"many2many:chld_authitem_child;References:Name;constraint:OnUpdate:CASCADE,OnDelete:SET NULL;" json:"child"`
CreatedAt time.Time `gorm:"default:CURRENT_TIMESTAMP" json:"created_at"`
UpdatedAt time.Time `gorm:"default:CURRENT_TIMESTAMP" json:"updated_at"`
DeletedAt time.Time `gorm:"default:null" json:"deleted_at"`
}
- 2 回答
- 0 关注
- 124 浏览
添加回答
举报