main.go 943 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package main
  2. import (
  3. "fmt"
  4. "gorm.io/driver/mysql"
  5. "gorm.io/gorm"
  6. "gorm.io/gorm/logger"
  7. "time"
  8. )
  9. // 定义 User 模型
  10. type User struct {
  11. gorm.Model
  12. Name string
  13. Email string
  14. Test Test
  15. }
  16. type Model struct {
  17. ID uint `gorm:"primarykey"`
  18. CreatedAt *time.Time
  19. UpdatedAt *time.Time
  20. DeletedAt gorm.DeletedAt `gorm:"index"`
  21. }
  22. type Test struct {
  23. Model
  24. Name string
  25. }
  26. func main() {
  27. t := Test{
  28. Name: "test",
  29. }
  30. Created(&t)
  31. // 打印成功创建的消息
  32. fmt.Printf("User created with ID: %d\n", t.ID)
  33. }
  34. func Created(u *Test) {
  35. dsn := "root:lxz664278@tcp(106.54.33.152:33369)/gorm?charset=utf8mb4"
  36. db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
  37. Logger: logger.Default.LogMode(logger.Info),
  38. NowFunc: func() time.Time {
  39. location, _ := time.LoadLocation("America/New_York")
  40. return time.Now().In(location)
  41. },
  42. })
  43. if err != nil {
  44. panic("failed to connect database")
  45. }
  46. db.Model(Test{}).Create(u)
  47. }