gorm 关联及其CURD(一) | 青训营笔记

304 阅读1分钟

这是我参与「第三届青训营 -后端场」笔记创作活动的第2篇笔记。

本文章参考gorm官方文档:gorm.io/docs/

  1. belongs to 关联建立一个和另一个模型的一对一连接,使得模型声明每个实例都「属于」另一个模型的一个实例 。

gorm文档例子:

type User struct {
  gorm.Model
  Name string
}

// `Profile` belongs to `User`
type Profile struct {
  gorm.Model
  UserID int
  User   User
  Name   string
}

在抖音项目中,video中字段Author即为该类型

// video belongs to Author
// change the foreignkey with `gorm:"foreignkey:AuthorId"`
type Video struct {
	VideoId       int64  `json:"id,omitempty" gorm:"primaryKey"`
	Author        User   `json:"author" gorm:"foreignkey:AuthorId"`
	AuthorId      int64  `json:"author_id"`
	PlayUrl       string `json:"play_url" json:"play_url,omitempty"`
	CoverUrl      string `json:"cover_url,omitempty"`
	Title         string `json:"title"`
	FavoriteCount int64  `json:"favorite_count,omitempty"`
	CommentCount  int64  `json:"comment_count,omitempty"`
	IsFavorite    bool   `json:"is_favorite,omitempty"`
	FavoriteUsers []User `gorm:"many2many:user_videos"`
	CreateTime    string `json:"create_time"`
}

  1. has one 关联也是与另一个模型建立一对一的连接,但语义(和结果)有些不同。 此关联表示模型的每个实例包含或拥有另一个模型的一个实例。

gorm 文档例子:

// 用户有一个信用卡,CredtCardID 外键
type User struct {
    gorm.Model
    CreditCard   CreditCard
}

type CreditCard struct {
    gorm.Model
    Number   string
    UserID    uint
}

CURD操作: 可以通过preload预加载关联 抖音项目实例:

type Video struct {
	VideoId       int64  `json:"id,omitempty" gorm:"primaryKey"`
	Author        User   `json:"author" gorm:"foreignkey:AuthorId"`
	AuthorId      int64  `json:"author_id"`
	PlayUrl       string `json:"play_url" json:"play_url,omitempty"`
	CoverUrl      string `json:"cover_url,omitempty"`
	Title         string `json:"title"`
	FavoriteCount int64  `json:"favorite_count,omitempty"`
	CommentCount  int64  `json:"comment_count,omitempty"`
	IsFavorite    bool   `json:"is_favorite,omitempty"`
	FavoriteUsers []User `gorm:"many2many:user_videos"`
	CreateTime    string `json:"create_time"`
}

func GetVideoById(videoId int64) *Video {
	var video Video
	DB.Table(constdef.VideosTableName).
		Preload("Author").
		Where("video_id = ?", videoId).
		First(&video)
	return &video
}

func CreateVideo(author *User, playUrl string, coverUrl string, title string) {
	video := &Video{
		Author:     *author,
		AuthorId:   author.UserId,
		PlayUrl:    playUrl,
		CoverUrl:   coverUrl,
		Title:      title,
		CreateTime: time.Now().Format("2006-01-02 15:04:05"),
	}
	DB.Table(constdef.VideosTableName).
		Preload("Author").
		Create(video)
}

func GetPublishedVideosByUserId(userId int64) []Video {
	var videos []Video
	DB.Table(constdef.VideosTableName).
		Preload("Author").
		Where("author_id = ?", userId).
		Find(&videos)
	return videos
}