Open shuvigoss opened 5 years ago
1对多或者1对1
package one2many
import (
"encoding/json"
"fmt"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
"testing"
"time"
)
type Person struct {
gorm.Model
Name string `gorm:"size:64;index:name_index"` //大小64,索引
Age int
IdCard IdCard
Emails []Email
}
func (p Person) String() string {
bytes, _ := json.Marshal(p)
return string(bytes)
}
type IdCard struct {
gorm.Model
Numbers string
PersonId uint
Expiry time.Time
}
type Email struct {
gorm.Model
Address string `gorm:"type:varchar(100)"`
PersonId uint
}
func TestOne(t *testing.T) {
db, err := gorm.Open("sqlite3", "test.db")
if err != nil {
panic("failed to connect database")
}
db.LogMode(true)
db.AutoMigrate(&Person{}, &IdCard{}, &Email{})
createData(db)
//查询某个用户的全部信息
findPerson(db)
//查询所有用户的全部信息
findPersons(db)
defer db.Close()
}
func findPersons(db *gorm.DB) {
var people []Person
db.Preload("Emails").Preload("IdCard").Find(&people)
//两种方式都可以
var perple1 []Person
db.Set("gorm:auto_preload", true).Find(&perple1)
fmt.Println(people)
fmt.Println(perple1)
}
func findPerson(db *gorm.DB) {
var p Person
db.First(&p, 1)
db.Model(&p).Related(&p.IdCard).Related(&p.Emails)
fmt.Println(p)
}
func createData(db *gorm.DB) {
p1 := Person{Name: "shuwei", Age: 18,
IdCard: IdCard{Numbers: "111111111111", Expiry: time.Now()},
Emails: []Email{{Address: "shuvigoss@gmail.com"}, {Address: "241883644@qq.com"}},
}
p2 := Person{Name: "zhangsan", Age: 18,
IdCard: IdCard{Numbers: "22222222", Expiry: time.Now()},
Emails: []Email{{Address: "zhangsan@example.com"}, {Address: "zhangsan@qq.com"}},
}
db.Create(&p1).Create(&p2)
}
多对多情况