Search code examples
gomany-to-manygo-gorm

many2many in Gorm, really


I'm trying to use the many-to-many relationship in gorm. However, the example is a partial snippet, and my attempt at creating a similar example snippet is failing.

package main

import (
    "github.com/jinzhu/gorm"
    _ "github.com/mattn/go-sqlite3"
)

type Part struct {
    gorm.Model

    Name string
}

type Machine struct {
    gorm.Model

    Name     string
    Subtasks []Part `gorm:"many2many:parts;"`
}

func main() {
    // Connect to the database
    db, err := gorm.Open("sqlite3", "example.db")
    if err != nil {
        panic(err)
    }
    defer db.Close()
    db.LogMode(true)

    // Set up associations
    if err := db.CreateTable(&Part{}).Error; err != nil {
        panic(err)
    }
    if err := db.CreateTable(&Machine{}).Related(&[]Part{}).Error; err != nil {
        panic(err)
    }
}

This panics on the last CreateTable call: panic: invalid association []


Solution

  • I think you have to drop the Related-part. CreateTable doesnt need it as far as i can see.

    if err := db.CreateTable(&Machine{}).Error; err != nil {
        panic(err)
    }
    

    Works for me