这是我参与「第五届青训营 」伴学笔记创作活动的第 7 天
使用First()操作报错: Scan error on column index 1, name “created_at“: unsupported Scan, storing driver.Value type []uint8 原因:连接数据库时配置未添加
parseTime=True
正确格式
dsn := "root:123456@tcp(127.0.0.1:3306)/simple-tiktok?charset=utf8mb4&parseTime=True&loc=Local"
db, err := gorm.Open(
mysql.Open(dsn),
&gorm.Config{})
关于db.Create()的注意事项
开始我想用Create()创建一张新的空表 像这样:
result := db.Create(&Video{})
但是并不能,报错:
Error 1146 (42S02): Table 'simple-tiktok.videos' doesn't exist
使用Create()必须放入至少一条数据,如果该表存在则插入这一条(多条)数据,若不存在则创建一张表再插入数据
如果我们想创建一张(多张)新的空表则如下
db.AutoMigrate(&Video{})
db.AutoMigrate(&User{}, &Product{}, &Order{})
在项目开发中,我们可能会随时调整声明的模型,比如添加字段和索引,使用 GORM 的自动迁移功能,可以始终让我们的数据库表结构保持最新。
此外,GORM 还提供了一些迁移接口的方法,可以帮助我们方便操作数据库表、字段和索引。
AutoMigrate 用于自动迁移你的 schema(模式),保持你的 schema(模式) 是最新的
注意: AutoMigrate 会创建表、缺失的外键、约束、列和索引。 并且会更改现有列的类型,如果大小、精度、是否为空可以更改。 但不会删除未使用的列,以保护您的数据。(只增不减)
定义接口(结构体)
我的Video接口
type Video struct {
gorm.Model
videoInf controller.Video
}
但创建的表中没有controller.Video中的字段
Grom的Model中只要接口名,应该改为
type Video struct {
gorm.Model
controller.Video
}
问题:但是我的controller.Video接口中包含User接口,不知道能不能行?
type Video struct {
Id int64 `json:"id,omitempty"`
Author User `json:"author"`
PlayUrl string `json:"play_url" json:"play_url,omitempty"`
CoverUrl string `json:"cover_url,omitempty"`
FavoriteCount int64 `json:"favorite_count,omitempty"`
CommentCount int64 `json:"comment_count,omitempty"`
IsFavorite bool `json:"is_favorite,omitempty"`
}
果然报错:
invalid field found for struct github.com/lpercc/simple-TikTok/repository.Video's field Author: define a valid foreign key for relations or implement the Valuer/Scanner interface
解决:在User后加gorm:"embedded"标识
type Video struct {
Id int64 `json:"id,omitempty"`
Author User `json:"author" gorm:"embedded"`
PlayUrl string `json:"play_url" json:"play_url,omitempty"`
CoverUrl string `json:"cover_url,omitempty"`
FavoriteCount int64 `json:"favorite_count,omitempty"`
CommentCount int64 `json:"comment_count,omitempty"`
IsFavorite bool `json:"is_favorite,omitempty"`
}
实际上最后我没有采用这种方法,因为User.Id和Video.Id会重复,在表中只有Id字段
采用这种结构,AuthorId 连接到 User.Id
type VideoDb struct {
Id int64 `gorm:"primaryKey"`
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt gorm.DeletedAt `gorm:"index"`
AuthorId int64
PlayUrl string
CoverUrl string
FavoriteCount int64
CommentCount int64
IsFavorite bool
}