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)
}
