package main

import (
	"fmt"

	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
)

type User struct {
	ID      uint   `gorm:"primaryKey"`
	Name    string `gorm:"size:100"`
	Profile Profile
	Orders  []Order
}

type Profile struct {
	ID     uint `gorm:"primaryKey"`
	UserID uint
	Bio    string `gorm:"size:200"`
}

type Order struct {
	ID      uint `gorm:"primaryKey"`
	UserID  uint
	Product string `gorm:"size:100"`
}

func main() {
	db, _ := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
	db.AutoMigrate(&User{}, &Profile{}, &Order{})

	// 创建测试数据
	//user := User{
	//	Name:    "Alice",
	//	Profile: Profile{Bio: "Software Engineer"},
	//	Orders: []Order{
	//		{Product: "Laptop"},
	//		{Product: "Mouse"},
	//	},
	//}
	//db.Create(&user)

	// 1. 预加载单个关联
	//var user1 User
	//db.Preload("Profile").First(&user1, 1)
	//fmt.Printf("User: %s, Bio: %s\n", user1.Name, user1.Profile.Bio)

	//// 2. 预加载多个关联
	//var user2 User
	//db.Preload("Profile").Preload("Orders").First(&user2, 1)
	//fmt.Printf("User: %s, Orders: %d\n", user2.Name, len(user2.Orders))

	// 3. 预加载所有关联
	//var user3 User
	//db.Preload("Profile").Preload("Orders").First(&user3, 1)
	//fmt.Printf("Fully loaded user: %s\n", user3.Name)

	//// 4. 条件预加载
	var user4 User
	db.Preload("Orders", "product = ?", "Laptop").First(&user4, 1)
	fmt.Printf("Filtered orders: %d\n", len(user4.Orders))
}
