Skip to content

Instantly share code, notes, and snippets.

@tkc
Last active August 17, 2016 06:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tkc/41088559d769480c1698eee484f1f57c to your computer and use it in GitHub Desktop.
Save tkc/41088559d769480c1698eee484f1f57c to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
)
type Product struct {
Id int64 `json:"id" gorm:"column:id;primary_key"`
Code string `json:"code" gorm:"column:code" sql:"not null;type:varchar(200)"
Price int8 `json:"price" gorm:"column:price" sql:"not null;type:int"
CreatedAt time.Tim `json:"created_at" gorm:"column:created_at" sql:"not null;type:datetime"`
UpdatedAt time.Time `json:"updated_at" gorm:"column:updated_at" sql:"not null;type:datetime"
}
func main() {
var product Product
var products [] Product
// Connect
db, err := gorm.Open("mysql", "root:secret@/go_test?charset=utf8&parseTime=True&loc=Local")
if err != nil {
panic("failed to connect database")
}
// Migrate
db.AutoMigrate(&Product{})
// Create
db.Create(&Product{Code: "test_code", Price: 1000})
// Read
db.First(&product, 1)
//fmt.Println(product)
db.First(&product, "code = ?", "test_code")
//fmt.Println(product)
db.Order("price desc, code").Find(&products)
//fmt.Println(products)
db.Select("code,price").Find(&products)
//fmt.Println(products)
// Update
db.Model(&product).Update("Price", 5000)
//fmt.Println(product)
for _, v := range products {
fmt.Print(v.Code)
fmt.Print(v.Price)
}
//Delete
db.Delete(&product)
}
type Post struct {
Id int64 `json:"id" gorm:"column:id;primary_key"`
Uuid string `json:"uuid" gorm:"column:uuid" sql:"not null;type:varchar(200)"`
Name string `json:"name" gorm:"column:name" sql:"not null;type:varchar(50)"`
CategoryId int8 `json:"category_id" gorm:"column:category_id" sql:"not null;type:int"`
PrefId int8 `json:"pref_id" gorm:"column:pref_id" sql:"not null;type:int"`
PvCount int64 `json:"pv_count" gorm:"column:pv_count" sql:"not null;int"`
LikeCount int64 `json:"like_count" gorm:"column:like_count" sql:"not null;type:int"`
Youtubu string `json:"youtubu" gorm:"column:you_tubu" sql:"type:text"`
CreatedAt time.Tim `json:"created_at" gorm:"column:created_at" sql:"not null;type:datetime"`
UpdatedAt time.Time `json:"updated_at" gorm:"column:updated_at" sql:"not null;type:datetime"`
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment