Gorm的关联关系

model.go

package models

import "github.com/jinzhu/gorm"
import _ "github.com/jinzhu/gorm/dialects/sqlite"

type Email struct {
	gorm.Model
	Email string
	UserID uint
}

// User 拥有并属于多种 Language,使用 `user_languages` 连接表
type User struct {
	gorm.Model
	Name string
	BillingAddress Address
	ShippingAddress Address
	Emails []Email
	Languages         []Language `gorm:"many2many:user_languages;"`
}

type Language struct {
	gorm.Model
	Name string
	Users               []*User     `gorm:"many2many:user_languages;"`
}
type Address struct {
	gorm.Model
	Address1 string
	UserID uint
}

model_test.go

package models

import (
	"github.com/jinzhu/gorm"
	"testing"
)
import _ "github.com/jinzhu/gorm/dialects/sqlite"

func TestAsso(t *testing.T) {

	db, err := gorm.Open("sqlite3", "./gorm.db")
	if err != nil {
		t.Error(err)
	}
	defer db.Close()
	db.LogMode(true)
	db.AutoMigrate(&User{}, &Address{}, &Email{}, &Language{})
	addr := Address{Address1: "My addr"}
	db.Save(&addr)
	user := User{
		Name:            "jinzhu",
		BillingAddress:  addr,
		ShippingAddress: Address{Address1: "Shipping Address - Address 1"},
		Emails: []Email{
			{Email: "[email protected]"},
			{Email: "[email protected]"},
		},
		Languages: []Language{
			{Name: "ZH"},
			{Name: "EN"},
		},
	}

	// 对于主键为空的item,不去创建
	//db.Debug().Set("gorm:association_autocreate", false).Create(&user)
	// 对于主键非空的item,不去更新,即:只保存外键关联那个字段,不更新关联对象的值
	//db.Debug().Set("gorm:association_autoupdate", false).Create(&user)
	// 不更新外健
	//db.Debug().Set("gorm:association_save_reference", false).Create(&user)
	// 默认上述开关全打开
	db.Create(&user)

	//db.Debug().Set("gorm:association_autocreate", false).
	//	Set("gorm:association_autoupdate", false).
	//	Set("gorm:association_save_reference", false).
	//	Create(&user)


	langs := []Language{}
	// 查找关联
	db.Model(&user).Association("Languages").Find(&langs)

	emails := []Email{}
	db.Model(&user).Association("Emails").Find(&emails)
	// 添加关联
	db.Model(&user).Association("Emails").Append(Email{Email: "[email protected]"})

	// 替换关联, 如果item主键为空,默认会新建
	email := emails[0]
	db.Model(&user).Association("Emails").Replace([]Email{email, {Email: "[email protected]"}})

	// 删除关联,item主键非空才生效
	def := Email{}
	db.First(&def, "Email = ?", "[email protected]")
	db.Model(&user).Association("Emails").Delete(def)

	// 清空关联,无论是替换,删除,还是清空,只会删除关联的引用,不会删除关联本身
	db.Model(&user).Association("Emails").Clear()

	print("ok")

}

你可能感兴趣的:(go)