many2many in Gorm, really

huangapple go评论88阅读模式
英文:

many2many in Gorm, really

问题

我正在尝试使用gorm中的多对多关系。然而,示例只是一个部分代码片段,我尝试创建一个类似的示例代码片段失败了。

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() {
	// 连接数据库
	db, err := gorm.Open("sqlite3", "example.db")
	if err != nil {
		panic(err)
	}
	defer db.Close()
	db.LogMode(true)

	// 设置关联关系
	if err := db.CreateTable(&Part{}).Error; err != nil {
		panic(err)
	}
	if err := db.CreateTable(&Machine{}).Error; err != nil {
		panic(err)
	}
	db.Model(&Machine{}).Association("Subtasks").Append(&Part{Name: "Part 1"})
}

在最后一个CreateTable调用中出现错误: panic: invalid association []

英文:

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 []

答案1

得分: 0

我认为你需要删除Related部分。据我所见,CreateTable不需要它。

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

对我来说可以工作。

英文:

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

huangapple
  • 本文由 发表于 2016年1月10日 08:08:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/34700479.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定