model.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package tests
  2. import (
  3. "database/sql"
  4. "time"
  5. "github.com/jinzhu/gorm"
  6. )
  7. // User has one `Account` (has one), many `Pets` (has many) and `Toys` (has many - polymorphic)
  8. // He works in a Company (belongs to), he has a Manager (belongs to - single-table), and also managed a Team (has many - single-table)
  9. // He speaks many languages (many to many) and has many friends (many to many - single-table)
  10. // His pet also has one Toy (has one - polymorphic)
  11. type User struct {
  12. gorm.Model
  13. Name string
  14. Age uint
  15. Birthday *time.Time
  16. Account Account
  17. Pets []*Pet
  18. Toys []Toy `gorm:"polymorphic:Owner"`
  19. CompanyID *int
  20. Company Company
  21. ManagerID uint
  22. Manager *User
  23. Team []User `gorm:"foreignkey:ManagerID"`
  24. Languages []Language `gorm:"many2many:UserSpeak"`
  25. Friends []*User `gorm:"many2many:user_friends"`
  26. Active bool
  27. }
  28. type Account struct {
  29. gorm.Model
  30. UserID sql.NullInt64
  31. Number string
  32. }
  33. type Pet struct {
  34. gorm.Model
  35. UserID uint
  36. Name string
  37. Toy Toy `gorm:"polymorphic:Owner;"`
  38. }
  39. type Toy struct {
  40. gorm.Model
  41. OwnerID string
  42. OwnerType string
  43. }
  44. type Company struct {
  45. ID int
  46. Name string
  47. }
  48. type Language struct {
  49. Code string `gorm:"primarykey"`
  50. Name string
  51. }