Created
October 24, 2022 03:01
-
-
Save BrandonClapp/85c27adc1ba1e033886bc817343137ed to your computer and use it in GitHub Desktop.
gorm associations + CRUD
This file contains hidden or 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
package main | |
import ( | |
"gorm.io/driver/sqlite" | |
"gorm.io/gorm" | |
) | |
type Product struct { | |
gorm.Model | |
// gorm.Model adds ID, CreatedAt, UpdatedAt, DeletedAt | |
Code string | |
Price uint | |
CategoryID int | |
Category Category | |
} | |
type Category struct { | |
gorm.Model | |
Name string | |
} | |
func main() { | |
db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{}) | |
if err != nil { | |
panic("failed to connect database") | |
} | |
// Migrate the schema | |
db.AutoMigrate(&Product{}, &Category{}) | |
seed(db) | |
var product Product | |
// must .Preload("Category") to get Category property to load | |
// https://gorm.io/docs/preload.html | |
// db.First(&product, 1) // find product with id of 1 | |
db.Preload("Category").First(&product, "Code = ?", "D42") // find product with integer primary key | |
db.Model(&product).Update("Price", 200) // Update single column | |
db.Model(&product).Updates(Product{Price: 200, Code: "F42"}) // non-zero fields | |
db.Model(&product).Updates(map[string]interface{}{"Price": 200, "Code": "F42"}) | |
var workout Category | |
db.First(&workout, "Name = ?", "Workout") | |
db.Model(&product).Update("Category", &workout) // Update the category of product | |
// db.Delete(&product, 1) // delete product where id is 1 | |
db.Where("Code = ?", "F42").Delete(&Product{}) | |
} | |
func seed(db *gorm.DB) { | |
var category Category | |
result := db.First(&category, "Name = ?", "Tech") | |
if result.RowsAffected == 0 { | |
category := &Category{Name: "Tech"} | |
db.Create(category) | |
} | |
var workout Category | |
result = db.First(&workout, "Name = ?", "Workout") | |
if result.RowsAffected == 0 { | |
workout := &Category{Name: "Workout"} | |
db.Create(workout) | |
} | |
var product Product | |
result = db.First(&product, "Code = ?", "D42") | |
if result.RowsAffected == 0 { | |
product := &Product{Code: "D42", Category: category, Price: 100} | |
db.Create(&product) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment