初始化Go学习项目

This commit is contained in:
liumangmang
2025-12-26 17:56:02 +08:00
commit 7f4527d501
90 changed files with 3436 additions and 0 deletions

View File

@@ -0,0 +1,71 @@
package main
import (
"fmt"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
//type User struct {
// ID uint `gorm:"primaryKey"`
// Name string `gorm:"size:100"`
// Orders []Order
//}
//
//type Order struct {
// ID uint `gorm:"primaryKey"`
// UserID uint
// Product string `gorm:"size:100"`
// Amount int
//}
func main() {
db, _ := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
db.AutoMigrate(&User{}, &Order{})
//user := User{Name: "Alice"}
//db.Create(&user)
//查询用户根据名称
var user User
db.Where("name = ?", "Alice").First(&user)
//order1 := Order{Product: "Laptop"}
//order2 := Order{Product: "Mouse"}
//order3 := Order{Product: "Keyboard"}
// 1. Append - 添加关联
//db.Model(&user).Association("Orders").Append(&order1, &order2)
//fmt.Println("Orders appended")
// 2. Count - 统计关联数量
//count := db.Model(&user).Association("Orders").Count()
//fmt.Printf("Order count: %d\n", count)
// 4. Replace - 替换所有关联
//db.Model(&user).Association("Orders").Replace(&order3)
//查询订单 Keyboard
var order3 Order
db.Where("product = ?", "Keyboard").First(&order3)
// 5. Delete - 删除关联(不删除记录本身)
//db.Model(&user).Association("Orders").Delete(&order3)
//fmt.Println("Association deleted")
//fmt.Println("Orders replaced with Keyboard")
// 6. Clear - 清空所有关联
//db.Model(&user).Association("Orders").Append(&order3)
db.Model(&user).Association("Orders").Clear()
fmt.Println("All associations cleared")
// 3. Find - 查找关联
var orders []Order
db.Model(&user).Association("Orders").Find(&orders)
fmt.Println("Orders found:")
for _, o := range orders {
fmt.Printf(" - %s\n", o.Product)
}
}