2 回答

TA貢獻1804條經(jīng)驗 獲得超8個贊
關(guān)系更接近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同樣可以在我們不需要第二張表的地方實現(xiàn),并且可以使用帶有一個額外列的同一張表作為參考
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條經(jīng)驗 獲得超8個贊
我得出結(jié)論,我需要使用 many2many 關(guān)系,這里是案例的例子:
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 關(guān)注
- 148 瀏覽
添加回答
舉報