Files
learn-golang/Web开发/03go-gorm-demo/relation_has_one.go
liumangmang b010f82221 feat(auth): 添加完整的用户认证API项目
- 实现用户注册、登录、JWT令牌认证功能
- 集成Gin、GORM、Viper、Zap等框架
- 添加密码加密、数据库操作、中间件等完整功能
- 配置多环境支持、日志轮转、CORS处理
- 创建完整的项目结构和配置文件体系
2025-12-30 18:00:42 +08:00

52 lines
1.1 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package main
import (
"fmt"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
// 用户拥有一个账户
//type User struct {
// ID uint `gorm:"primaryKey"`
// Name string `gorm:"size:100"`
// Account Account // 一对一关联
// Email string `gorm:"size:100;unique"`
//}
//
//type Account struct {
// ID uint `gorm:"primaryKey"`
// UserID uint // 外键
// Balance int
//}
func main() {
db, _ := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
db.AutoMigrate(&User{}, &Account{})
// 1. 创建用户和账户
user := User{
Name: "Alice",
Account: Account{Balance: 1000},
}
db.Create(&user)
fmt.Println("User and account created")
// 2. 预加载查询
var result User
db.Preload("Account").First(&result, user.ID)
fmt.Printf("User: %s, Balance: %d\n", result.Name, result.Account.Balance)
// 3. 更新关联数据
db.Model(&result.Account).Update("balance", 2000)
fmt.Println("Account balance updated")
// 4. 删除关联(不会自动删除 Account
db.Delete(&result)
var accountCount int64
db.Model(&Account{}).Count(&accountCount)
fmt.Printf("Account still exists: %d\n", accountCount)
}