Access to many2many table data

Viewed 452

I want to work on a table many2many generated automatically by GORM db.AutoMigrate(&Document{}, &Folder{}).

In this scenario, a folder has documents and documents have folders, so far it's good, but the association has a status (valid, invalid ...) so I have to look at the documents_folders table to know the state.

Database:

+-----------------------+
| Table                 |
+-----------------------+
| documents             |
| documents_folders     |
| folders               |
+-----------------------+

Models :

Stuff

(ID primary_key == UUID)

type Stuff struct {
    ID          uuid.UUID  `gorm:"type:char(36);primary_key;" json:"id"`
    CreatedAt   time.Time  `json:"created_at"`
    UpdatedAt   time.Time  `json:"update_at"`
    DeletedAt   *time.Time `sql:"index" json:"deleted_at"`
}

Folder

type Folder struct {
    Stuff
    Name      string      `json:"name" form:"name" gorm:"name;"`
    Documents []*Document `json:"documents" gorm:"many2many:documents_folders;"`
}

Document

type Document struct {
    Stuff
    Name        string    `json:"name" form:"name" gorm:"name;"`
    Folders     []*Folder `json:"folders" gorm:"many2many:documents_folders;"`
}

DocumentsFolders

I created this model to access the table, it is generated automatically but I have to add the column State

type DocumentsFolders struct {
    DocumentID string    `json:"document_id" sql:"type:char(36) REFERENCES documents(id)"`
    Document   *Document `json:"document"`
    FolderID   string    `json:"folder_id" sql:"type:char(36) REFERENCES folders(id)"`
    Folder     *Folder   `json:"folder"`
    State      string    `json:"state" form:"state" gorm:"state;"`
}

I can not access it when I preload the document and folder like :

folder := Folder{}
db.Preload("Documents").Where("id = ?", "myUUID").First(&folder)

I would like to see the State of the document association.

Thanks for your help

1 Answers

You have the following problems:

  • You missed adding AutoMigrate for DocumentsFolders.
  • Don't use slices with pointers.

Check the below fixed example for more reference:

package main

import (
    "fmt"
    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/sqlite"
    "math/rand"
    "time"
)

type UUID = string

type Model struct {
    ID        UUID       `gorm:"type:char(36);primary_key;" json:"id"`
    CreatedAt time.Time  `json:"created_at"`
    UpdatedAt time.Time  `json:"update_at"`
    DeletedAt *time.Time `sql:"index" json:"deleted_at"`
}

type Folder struct {
    Model
    Name      string     `json:"name" form:"name" gorm:"name;"`
    Documents []Document `json:"documents" gorm:"many2many:documents_folders;"`
}

type Document struct {
    Model
    Name    string   `json:"name" form:"name" gorm:"name;"`
    Folders []Folder `json:"folders" gorm:"many2many:documents_folders;"`
}

type DocumentsFolders struct {
    DocumentID string    `json:"document_id" sql:"type:char(36) REFERENCES documents(id)"`
    Document   *Document `json:"document"`
    FolderID   string    `json:"folder_id" sql:"type:char(36) REFERENCES folders(id)"`
    Folder     *Folder   `json:"folder"`
    State      string    `json:"state" form:"state" gorm:"state;"`
}

var i = rand.Int()

func genId() string {
    id := i
    i++
    return fmt.Sprintf("%036d", id)
}

func main() {
    db, _ := gorm.Open("sqlite3", "./db.sqlite")
    db.AutoMigrate(&Document{}, &Folder{}, &DocumentsFolders{})

    folder1 := &Folder{
        Model:     Model{ID: genId()},
        Name:      "myFolder",
        Documents: nil,
    }
    db.FirstOrCreate(&folder1, folder1.ID)

    doc1 := &Document{
        Model:   Model{ID: genId()},
        Name:    "doc1",
    }
    db.FirstOrCreate(doc1, doc1.ID)

    doc2 := &Document{
        Model:   Model{ID: genId()},
        Name:    "doc2",
    }
    db.FirstOrCreate(doc2, doc2.ID)

    // join them
    db.Create(&DocumentsFolders{
        DocumentID: doc1.ID,
        FolderID:   folder1.ID,
        State:      "happy!",
    })
    db.Create(&DocumentsFolders{
        DocumentID: doc2.ID,
        FolderID:   folder1.ID,
        State:      "happy!",
    })

    // get the new folder to check
    db.Preload("Documents").First(folder1, folder1.ID)

    // two documents are printed
    fmt.Printf("Documents count: %d\n", len(folder1.Documents)) // prints 2
}
Related