gorm中一对一,多对多关系

1、一对一 : 属于 belongsTo

package main
// belongsTo
type Dog struct { //舔狗
	gorm.Model
	Name string

}

type GirlGod struct { //女神
	gorm.Model
	Name string
}

func (it *ServiceContext) AutoMigrate() {
	it.DB.AutoMigrate(&Dog{},&GirlGod{}) //创建这两张表,它们之间没有任何关联
}

// ==========================================================================================
// belongsTo
type Dog struct { //舔狗
	gorm.Model
	Name string
	GirlGodID uint
	GirlGod GirlGod //舔狗属于女神
}

type GirlGod struct { //女神
	gorm.Model
	Name string
}

func (it *ServiceContext) AutoMigrate() {
	it.DB.AutoMigrate(&Dog{}) //只创建Dog,因为 Dog belongsTo GirlGod,所以这里会自动创建2张表,但这2张表之间没什么关系
}

// ==========================================================================================
// belongsTo
type Dog struct { //舔狗
	gorm.Model
	Name string
	GirlGodID uint
	GirlGod GirlGod //舔狗属于女神
}

type GirlGod struct { //女神
	gorm.Model
	Name string
}

func (it *ServiceContext) AutoMigrate() {
	g := GirlGod{
		Model:gorm.Model{
			ID: 1,
		},
		Name: "淼淼",
	}
	d := Dog{
		Model:gorm.Model{
			ID: 1,
		},
		Name: "奇奇",
		GirlGod: g,
	}
	it.DB.AutoMigrate(&Dog{}) //只创建Dog,因为 Dog belongsTo GirlGod,所以这里会自动创建2张表,但这2张表之间没什么关系
	it.DB.Create(&d) // 在 GirlGod{}, Dog{},表中分别创建一条记录 (两个表通过 Dog{} 中的 girl_god_id 字段关联)
}

// ==========================================================================================
// has one
type GirlGod struct { //女神
	gorm.Model
	Name string
	Dog	Dog    // 女神拥有舔狗 has one
}

type Dog struct { //舔狗
	gorm.Model
	Name string
	GirlGodID uint //狗链子被女神牵着
}

func (it *ServiceContext) AutoMigrate() {
	d := Dog{
		Model:gorm.Model{
			ID: 1,
		},
		Name: "奇奇",
	}
	g := GirlGod{
		Model:gorm.Model{
			ID: 1,
		},
		Name: "淼淼",
		Dog: d,
	}
	it.DB.AutoMigrate(&GirlGod{},&Dog{}) //只创建Dog,因为 Dog belongsTo GirlGod,所以这里会自动创建2张表,但这2张表之间没什么关系
	it.DB.Create(&g) // 在 GirlGod{}, Dog{},表中分别创建一条记录 (两个表通过 Dog{} 中的 girl_god_id 字段关联)
}

你可能感兴趣的:(Go,go)