zoukankan      html  css  js  c++  java
  • gorm 关系一对一,一对多,多对多查询

    建表

    要实现的功能.
    文章属于一个分类.
    文章有多个标签

    相关表四张。表提前在数据库建立的。没有外键关系

    • article 表
    • tag 表.
    • article_tag 表
    • category 表
    //文章表
    type Article struct {
      Id int `json:"id"`
      Title string `json:"title"`
      CategoryId int `json:"category_id"`
      Category Category `json:"category";gorm:"foreignkey:CategoryID"`//指定关联外键
      Tag []Tag `gorm:"many2many:article_tag" json:"tag"`//多对多关系.
      //article_tag表默认article_id字段对应article表id.tag_id字段对应tag表id
      //可以把对应sql日志打印出来,便于调试
    }
    
    //文章_标签中间表
    type ArticleTag struct {
       Id int `json:"id" `
      ArticleId string `json:"article_id"`
      TagId string `json:"tag_id"`
      CreatedAt string `json:"created_at"`
      UpdatedAt string `json:"updated_at"`
    }
    
    //标签表
    type Tag struct {
       Id int `json:"id" `
      TagName string `json:"tag_name"`
    }
    
    //分类表
    type Category struct {
       ID int `json:"id"`
      CategoryName string `json:"category_name"`
      Status int `json:"status"`
      CreatedAt time.Time `json:"created_at"`
      UpdatedAt time.Time `json:"updated_at"`
    }
    
    
    

    查一列

    //远程一对多.一对一
    func (a *Article) ListArticle(title string) (Article, error) {
       query := database.GormPool
      var article Article
      query.Where("title like ?", "%"+title+"%").First(&article)
       fmt.Println(article)
       err := query.Model(&article).
          Related(&article.Category).
          Related(&article.Tag, "tag").
          Find(&article).Error
      if err != nil && err != gorm.ErrRecordNotFound {
          return article, nil
      }
       return article, err
    }
    
    

    结果如图:一个分类,多个标签
    使用 Related 方法,需要先把 Article 查询好,
    然后根据 Article 定义中指定的 CategoryID 去查找 Category,
    查找标签,就直接定义标签接收 Tag 切片:然后写 gorm 的表对应关系:"many2many:article_tag"

    查多列表

    func (a *Article) ListArticle(title string) (articles []Article, err error) {
        query := database.GormPool
        err = query.Model(articles).
            Where("title like ?", "%"+title+"%").
            Preload("Category").
            Preload("Tag").Find(&articles).Error
        if err != nil && err != gorm.ErrRecordNotFound {
            return
        }
        return
    }
    

  • 相关阅读:
    jvisualm 结合 visualGC 进行jvm监控,并分析垃圾回收
    linux 查看服务器cpu 与内存配置
    arthas 使用总结
    selinux contexts 安全上下文的临时更改
    Android 8.1 Doze模式分析(五) Doze白名单及Debug方式
    Window 任意窗口置顶软件Window TopMost Control
    Android ApkToolPlus一个可视化的跨平台 apk 分析工具
    SVN Please execute the 'Cleanup' command.
    Android 如何在64位安卓系统中使用32位SO库
    Android cmd命令查看apk是32位还是64位?
  • 原文地址:https://www.cnblogs.com/haima/p/12849729.html
Copyright © 2011-2022 走看看