主键(Primary Key)
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"
}
func (u User) TableName() string {
If u.Role == "admin" {
return "admin_users"
} else {
return "users"
}
}
// 禁用默认表名的复数形式,如果设置为true,则`User`的默认表名是`user`
db.SingularTable(true)也可以通过Table()指定表名:
// 使用User结构体创建名为`deleted_users`的表
db.Table("deleted_users").CreateTable(&User{})
var deleted_users []user
db.Table("deleted_users").Find(&deleted_users)
// SELECT * FROM deleted_users;
db.Table("deleted_users").Where("name = ?","jinzhu").Delete()
// DELETE FROM deleted_users WHRER name = 'jinzhu';
GORM还支持更改默认表名称规则:
gorm.DefaultTableNameHandler = func(db *gorm.DB, defaultTableName string) string {
return "prefix_" + defaultTableName;
}列名(Column Name)
列名由字段名称进行下划线分割来生成。
type User struct {
ID unit // column name is `id`
Name string // column name is `name`
Birthday string // comumn name is `birthday`
CreateAt time.Time // column name is `created_at`
}可以使用结构体tag指定列名:
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`
}