mptt plugin for gorm orm
move node up and down- reparent
- scope
- add tree configuration
- level
- id varchar 36 (uuid v4)
- parent_id varchar 36 (uuid v4) index
- lft int index
- rght int
A simple model example:
type Category struct {
ID string `gorm:"primaryKey;type:varchar(36)"`
ParentId *string `gorm:"default:null;index;type:varchar(36)"`
Name string `gorm:"default:null;type:varchar(100)"`
Lft int `gorm:"index"`
Rght int
}
func (c *Category) BeforeCreate(tx *gorm.DB) (err error) {
// UUID version 4
c.ID = uuid.NewString()
return
}
import mptt "github.com/golgher/gorm-mptt"
# Gorm database connection
dsn := "host=localhost user=root password=1234 dbname=mptt port=5445 sslmode=disable TimeZone=America/Sao_Paulo"
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{
Logger: logger.Default.LogMode(logger.Info),
})
if err != nil {
panic("failed to connect database")
}
t := mptt.New(db)
Parent := entity.Category{
Name: "Main",
}
t.CreateNode(&Parent)
Child1 := entity.Category{
Name: "Child 1"
ParentId: &Parent.ID,
}
t.CreateNode(&Child1)
Child2 := entity.Category{
Name: "Child 2"
ParentId: &Parent.ID,
}
t.CreateNode(&Child2)
status, err := t.MoveUp(Child2, 1) //move one place up, if possible
status, err := t.MoveDown(Child2, 1) //move one place down, if possible
t.DeleteNode(&entity.Category{
ID: "a8c70ff6-6b4e-4caa-aebe-9ad368342c8e",
})