Created
March 31, 2020 09:19
-
-
Save jackbillstrom/e6eb705074d9e90384998a8397dd29ed to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Init MYSQL instance | |
// docker run --name mysql-api -e MYSQL_ROOT_PASSWORD=simsalabim -p 3306:3306 -d mysql | |
// docker exec -ti mysql-api mysql --user root --password | |
// > CREATE DATABASE honey; | |
package main | |
import ( | |
"fmt" | |
"github.com/jinzhu/gorm" | |
_ "github.com/jinzhu/gorm/dialects/mysql" | |
) | |
type Contract struct { | |
gorm.Model | |
Title string `gorm:"size:50;not null"` | |
CompanyName string `gorm:"size:255;not null"` | |
Period string `gorm:"size:50"` | |
Products []*Product | |
} | |
type Product struct { | |
gorm.Model | |
ContractID uint `gorm:"not null"` | |
Contract *Contract | |
Name string `gorm:"size:61;not null"` | |
Price string `gorm:"size:20";json:"price"` | |
Description string `gorm:"size:255;json:"description""` | |
} | |
func Connect() (*gorm.DB, error) { | |
return gorm.Open("mysql", "root:simsalabim@/honey?charset=utf8&parseTime=True&loc=Local") | |
} | |
func BoxString(x string) *string { | |
return &x | |
} | |
func Migrate(db *gorm.DB) { | |
contractPrototype := &Contract{} | |
productPrototype := &Product{} | |
db.AutoMigrate(contractPrototype, productPrototype) | |
// db.Model(productPrototype).AddForeignKey("contract_id", "contracts(id)", "RESTRICT", "CASCADE") | |
} | |
func Seed(db *gorm.DB) { | |
contact1 := &Contract{ | |
Title: "Kontrakt två", | |
CompanyName: "Företagsnamn", | |
Period: "2020-03-30 to 2021-03-29", | |
Products: []*Product{ | |
{ | |
Name: "SEO", | |
Price: "20000", | |
Description: "Beskrivning 1", | |
}, | |
{ | |
Name: "MP", | |
Price: "2999", | |
Description: "Beskrivning", | |
}, | |
}, | |
} | |
// db.Save(contract) | |
db.Save(contact1) | |
fmt.Printf("contracts created:\n%v\n%v\n", contact1) // ..a , b ) | |
} | |
func ListEverything(db *gorm.DB) { | |
contracts := []Contract{} | |
db.Preload("Products").Find(&contracts) | |
fmt.Printf("%+v\n", contracts) | |
} | |
func ClearEverything(db *gorm.DB) { | |
err1 := db.Delete(&Contract{}).Error | |
fmt.Printf("Deleting the records:\n%v\n", err1) | |
} | |
func main() { | |
if db, err := Connect(); err != nil { | |
fmt.Printf("⚠️ : No DB connection", err) | |
} else { | |
defer db.Close() | |
Migrate(db) | |
// Seed(db) | |
ListEverything(db) | |
// ClearEverything(db) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment