前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Gorm-模型关系定义和标签 (四)

Gorm-模型关系定义和标签 (四)

原创
作者头像
堕落飞鸟
发布2023-04-24 00:13:56
4050
发布2023-04-24 00:13:56
举报
文章被收录于专栏:飞鸟的专栏

示例

以下是一个完整的Gorm模型定义示例:

代码语言:javascript
复制
package models

import (
    "gorm.io/gorm"
)

type User struct {
    gorm.Model
    Name      string `gorm:"uniqueIndex"`
    Age       int    `gorm:"index"`
    Gender    string `gorm:"size:255;not null"`
    CreatedAt time.Time `gorm:"autoCreateTime"`
    UpdatedAt time.Time `gorm:"autoUpdateTime"`
    DeletedAt *time.Time `gorm:"index"`
    Articles []Article
    Roles    []Role `gorm:"many2many:user_roles;"`
}

type Article struct {
    gorm.Model
    Title     string
    Content   string
    UserID    uint
    User      User `gorm:"foreignKey:UserID"`
    Comments  []Comment
    Categories []Category `gorm:"many2many:article_categories;"`
}

type Comment struct {
    gorm.Model
    Content   string
    ArticleID uint
    Article   Article `gorm:"foreignKey:ArticleID"`
}

type Category struct {
    gorm.Model
    Name      string `gorm:"uniqueIndex"`
    Articles  []Article `gorm:"many2many:article_categories;"`
}

type Role struct {
    gorm.Model
    Name   string
    Users  []User `gorm:"many2many:user_roles;"`
}

在上述代码中,我们定义了四个模型:User、Article、Comment和Category,以及一个Role模型,用于演示BelongsTo、HasOne、HasMany和ManyToMany关系的使用。其中,User模型与Article模型使用了HasMany关系,Article模型与Comment模型使用了HasMany关系,Article模型与Category模型使用了ManyToMany关系,User模型与Role模型使用了ManyToMany关系。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 示例
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档