gorm_mptt

package module
v0.0.0-...-c07e81a Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 13, 2022 License: MIT Imports: 4 Imported by: 0

README

gorm-mptt

mptt plugin for gorm orm

TODO

  1. move node up and down
  2. reparent
  3. scope
  4. add tree configuration
  5. level

DOC

Database: requirements
  • 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
}

Enable Tree
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)
Create node

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)
Move up and down
status, err := t.MoveUp(Child2, 1) //move one place up, if possible
status, err := t.MoveDown(Child2, 1) //move one place down, if possible
Delete node
t.DeleteNode(&entity.Category{
	ID: "a8c70ff6-6b4e-4caa-aebe-9ad368342c8e",
})

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type MpttTree

type MpttTree interface {
	CreateNode(n interface{}) error
	DeleteNode(n interface{}) error
	MoveDown(n interface{}, pos int) (bool, error)
	MoveUp(n interface{}, pos int) (bool, error)
}

type Tree

type Tree gorm.DB

func New

func New(db *gorm.DB) *Tree

func (*Tree) CreateNode

func (db *Tree) CreateNode(n interface{}) error

func (*Tree) DeleteNode

func (db *Tree) DeleteNode(n interface{}) error

func (*Tree) MoveDown

func (db *Tree) MoveDown(n interface{}, pos int) (bool, error)

func (*Tree) MoveUp

func (db *Tree) MoveUp(n interface{}, pos int) (bool, error)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL