// gorm.Model 定义 type Model struct { ID uint`gorm:"primary_key"` CreatedAt time.Time UpdatedAt time.Time DeletedAt *time.Time }
// Inject fields `ID`, `CreatedAt`, `UpdatedAt`, `DeletedAt` into model `User` // 将 `ID`, `CreatedAt`, `UpdatedAt`, `DeletedAt`字段注入到`User`模型中 type User struct { gorm.Model Name string }
// 不使用gorm.Model定义模型 type User struct { ID int Name string }
ID 作为主键
GORM 默认会使用名为ID的字段作为表的主键。
type User struct { ID string// 名为`ID`的字段会默认作为表的主键 Name string }
// 使用`AnimalID`作为主键 type Animal struct { AnimalID int64`gorm:"primary_key"` Name string Age int64 }
表名(Table Name)
表名默认就是结构体名称的复数,例如:
type User struct {} // 默认表名是 `users`
// 将 User 的表名设置为 `profiles` func(User)TableName()string { return"profiles" }
type User struct { ID uint// column name is `id` Name string// column name is `name` Birthday time.Time // column name is `birthday` CreatedAt time.Time // column name is `created_at` }
// Overriding Column Name type Animal struct { AnimalId int64`gorm:"column:beast_id"`// set column name to `beast_id` Birthday time.Time `gorm:"column:day_of_the_beast"`// set column name to `day_of_the_beast` Age int64`gorm:"column:age_of_the_beast"`// set column name to `age_of_the_beast` }