gorm连接数据库

package main

import (
	_ "github.com/go-sql-driver/mysql"
	"github.com/jinzhu/gorm"
)

type User struct {
	gorm.Model
	Name  string `gorm:"primary_key;column:user_name;type:varchar(100);"`

}
func (u User) TableName ()string{

		return "luckly_users"
}

func main() {
	db, _ := gorm.Open("mysql","root:xjg123456@tcp(127.0.0.1:3306)/gorm?charset=utf8&parseTime=True&loc=Local")
	//db.SingularTable(true)
	db.AutoMigrate(&User{})
	defer db.Close()

}

数据库之间的关联关系

package main

import (
   _ "github.com/go-sql-driver/mysql"
   "github.com/jinzhu/gorm"
)
type Class struct {
   gorm.Model
   ClassName string
   Students []Student

}
type Student struct {
   gorm.Model
ClassID uint
   StudentName string
IDCard IDCard
   //多对多 后看
Teachers []Teacher `gorm:"many2many:student_teachers;"`
//TeacherID uint


}
type IDCard struct {
   gorm.Model
   StudentID uint
    Num int

}
type Teacher struct {
   gorm.Model
   TeacherName string
   //StudentID uint
   Students []Student`gorm:"many2many:student_teachers;"`

}




func main() {
   db, _ := gorm.Open("mysql","root:xjg123456@tcp(127.0.0.1:3306)/gorm?charset=utf8&parseTime=True&loc=Local")
   //db.SingularTable(true)
   db.AutoMigrate(&Teacher{},&Class{},&Student{},&IDCard{})
   i:=IDCard{
      Num: 123456,
   }

   s:=Student{
      StudentName: "luckly",
      IDCard: i,
   }

   t:=Teacher{
      TeacherName: "老师",
      Students: []Student{s},
   }
   c:=Class{
      ClassName: "七七的班级",
      Students: []Student{s},
   }
 _ =db.Create(&c).Error
   _ =db.Create(&t).Error

   defer db.Close()

}