gorm试用

####gorm试用--属于

###数据库连接

	db, err := gorm.Open("mysql", "root:rootpassword@/dbname?charset=utf8&parseTime=True&loc=Local")
	if err != nil {
		panic("连接数据库失败")
	}
	defer db.Close()

###创建表

	if !db.HasTable(&User{}) {
		db.CreateTable(&User{})
	}
  
	if !db.HasTable(&Profile{}) {
		db.CreateTable(&Profile{})
	}

###准备些数据

	oneuser := User{Name: "wayne"}
	db.Create(&oneuser)
	oneprofile := Profile{UserID: 1, Name: "wayne1"}
	db.Create(&oneprofile)

###查询数据

user := &User{}
db.Debug().Where(&User{Name: "wayne"}).First(&user)
profile := &Profile{}
db.Debug().Model(&user).Related(&profile)

fmt.Println(user)
fmt.Println(profile)

###整体代码

    package main

    import (
    	"fmt"
    	"github.com/jinzhu/gorm"
    	_ "github.com/jinzhu/gorm/dialects/mysql"
    )

    func main() {
    	db, err := gorm.Open("mysql", "root:rootpassword@/dbname?charset=utf8&parseTime=True&loc=Local")
    	if err != nil {
    		panic("连接数据库失败")
    	}
    	defer db.Close()

    	if !db.HasTable(&User{}) {
    		db.CreateTable(&User{})
    	}
      
    	if !db.HasTable(&Profile{}) {
    		db.CreateTable(&Profile{})
    	}

    	oneuser := User{Name: "wayne"}
    	db.Create(&oneuser)
    	oneprofile := Profile{UserID: 1, Name: "wayne1"}
    	db.Create(&oneprofile)

    	user := &User{}
        // 查询用户,条件为名字为wayne,将结果放到user变量里
    	db.Debug().Where(&User{Name: "wayne"}).First(&user)
    	profile := &Profile{}
        // 依据之前查询的user为条件,查询profile,查询profile的条件为user的id
    	db.Debug().Model(&user).Related(&profile)

    	fmt.Println(user)
    	fmt.Println(profile)
    }

    type User struct {
    	gorm.Model
    	Name string
    }

    type Profile struct {
    	gorm.Model
    	UserID int
    	User   User
    	Name   string
    }

猜你喜欢

转载自my.oschina.net/u/943306/blog/1622075
今日推荐