gorm tips
约定的列名
type User struct {
ID uint // 列名是 `id`
Name string // 列名是 `name`
Birthday time.Time // 列名是 `birthday`
CreatedAt time.Time // 列名是 `created_at`
}
约定的是驼峰命名会转化为下划线命名。
type Animal struct {
AnimalID int64 `gorm:"column:beast_id"` // 将列名设为 `beast_id`
Birthday time.Time `gorm:"column:day_of_the_beast"` // 将列名设为 `day_of_the_beast`
Age int64 `gorm:"column:age_of_the_beast"` // 将列名设为 `age_of_the_beast`
}
可以使用标签修改对用的名字。不然可能导致查出来的数据转换不到对应结构体中。
指定查询字段
不指定的化,是用的 select *。还可以对字段使用函数,但是要加上 as 不然会导致结构体中没有对象字段的值。
db.Table("users").Select("COALESCE(age,?)", 42).Rows()
// SELECT COALESCE(age,'42') FROM users;
db.Select("title", "id", "DATE_FORMAT(resolvedDate,'%Y-%m-%d') as resolvedDate")
浙公网安备 33010602011771号