0%

gorm.Model的包含字段

gorm.Model源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package gorm

import "time"

// Model base model definition, including fields `ID`, `CreatedAt`, `UpdatedAt`, `DeletedAt`, which could be embedded in your models
// type User struct {
// gorm.Model
// }
type Model struct {
ID uint `gorm:"primary_key"`
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt *time.Time `sql:"index"`
}

所以我们创建结构体的时候的就不需要包含这几个字段了,不然后会报错

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import (
"time"
)

type User struct {
Id int `json:"id" form:"id" gorm:"primary_key"` // 主键ID
CreatedAt time.Time `gorm:""json:"createdAt"` // 创建时间
UpdatedAt time.Time `gorm:""json:"updatedAt"` // 更新时间
DeletedAt *time.Time `gorm:"index"json:"deletedAt"` // 删除时间
Name string `gorm:"not null;"json:"name"` // 姓名
...
}

func (*User) TableName() string {
return "user"
}

func (m *User) IsAdministrator() bool {
if m == nil || m.Id <= 0 {
return false
}
return m.Role == 0 || m.Role == 1
}

报错

1
2
3
4
5
6
7
8
9
10
11
12
13
panic: Error 1146: Table 'XXXX.user' doesn't exist

goroutine 1 [running]:
github.com/jinzhu/gorm.mysql.HasIndex(0x1a3ebc0, 0xc0000fe240, 0x203000, 0x19037e8, 0x4, 0xc00059ddc0, 0x13, 0x30c8300)
/Users/samtake/go/pkg/mod/github.com/jinzhu/gorm@v1.9.12/dialect_mysql.go:189 +0x31f
github.com/jinzhu/gorm.(*Scope).addIndex(0xc0004ec380, 0x18ecd00, 0xc00059ddc0, 0x13, 0xc00037b5a0, 0x2, 0x2)
/Users/samtake/go/pkg/mod/github.com/jinzhu/gorm@v1.9.12/scope.go:1212 +0x8d
github.com/jinzhu/gorm.(*DB).AddIndex(0xc00001dee0, 0xc00059ddc0, 0x13, 0xc00037b5a0, 0x2, 0x2, 0x1)
/Users/samtake/go/pkg/mod/github.com/jinzhu/gorm@v1.9.12/main.go:706 +0xac
github.com/jinzhu/gorm.(*Scope).autoIndex(0xc000559900, 0xc000559900)
/Users/samtake/go/pkg/mod/github.com/jinzhu/gorm@v1.9.12/scope.go:1312 +0x9a0
github.com/jinzhu/gorm.(*Scope).createTable(0xc000559900, 0x19037e8)
/Users/samtake/go/pkg/mod/github.com/jinzhu/gorm@v1.9.12/scope.go:1194 +0x792

改成

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import (
"time"

"github.com/jinzhu/gorm"
)

type User struct {
gorm.Model
Name string `gorm:"not null;"json:"name"` // 姓名
...
}

func (*User) TableName() string {
return "user"
}

func (m *User) IsAdministrator() bool {
if m == nil || m.ID <= 0 {
return false
}
return m.Role == 0 || m.Role == 1
}