// gorm.Model definition
type Model struct {
ID uint `gorm:"primary_key"`
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt *time.Time
}
模型
模型定义
1
2
3
4
5
6
7
8
9
10
11
// Inject fields `ID`, `CreatedAt`, `UpdatedAt`, `DeletedAt`into model `User`type User struct {
gorm.Model
Name string
}
// Declaring model w/o gorm.Model
type User struct {
ID int Name string
}
type User struct {
ID int// field named `ID` will be used asprimary field bydefault Name string
}
//Set field `AnimalID`asprimary field
type Animal struct {
AnimalID int64 `gorm:"primary_key"` Name string
Age int64
}
表名
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
type User struct {} //defaulttable name is`users`//SetUser's table name to be `profiles`
func (User) TableName() string {
return "profiles"
}
func (u User) TableName() string {
if u.Role == "admin" {
return "admin_users"
} else {
return "users"
}
}
// Disable table name's pluralization, ifsettotrue, `User`'s table name will be `user`
db.SingularTable(true)
//Create`deleted_users`tablewith struct User's definition
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 WHERE name = 'jinzhu';
列名
列名称将是该字段的名称是较低的蛇形列表
1
2
3
4
5
6
7
8
9
10
11
12
13
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"`//setcolumn name to`beast_id` Birthday time.Time`gorm:"column:day_of_the_beast"`//setcolumn name to`day_of_the_beast` Age int64 `gorm:"column:age_of_the_beast"`//setcolumn name to`age_of_the_beast`}
列元素
CreatedAt:行记录创建时间
1
2
3
db.Create(&user) // will set`CreatedAt`to current time//Tochange its value, you could use`Update`db.Model(&user).Update("CreatedAt", time.Now())
UpdatedAt:行记录更新时间
1
2
db.Save(&user) // will set`UpdatedAt`to current timedb.Model(&user).Update("name", "jinzhu") // will set`UpdatedAt`to current time
DeletedAt:行记录删除时间
1
2
3
4
5
6
7
8
9
10
db.Delete(&user)
// UPDATE users SET deleted_at="2013-10-29 10:23" WHERE id = 111;
// Batch Delete
db.Where("age = ?", 20).Delete(&User{})
// UPDATE users SET deleted_at="2013-10-29 10:23" WHERE age = 20;
// Delete record permanently with Unscoped
db.Unscoped().Delete(&order)
// DELETE FROM orders WHERE id=10;