登录
首页 >  Golang >  Go问答

如何正确进行gorm/go中的表连接操作?

来源:stackoverflow

时间:2024-02-14 13:36:23 184浏览 收藏

从现在开始,努力学习吧!本文《如何正确进行gorm/go中的表连接操作?》主要讲解了等等相关知识点,我会在golang学习网中持续更新相关的系列文章,欢迎大家关注并积极留言建议。下面就先一起来看一下本篇正文内容吧,希望能帮到你!

问题内容

我的消息结构;

type message struct {
  id          int    `json:"id" gorm:"primarykey;auto_increment"`
  message     string `json:"message"`
  sender      int    `json:"sender" gorm:"foreignkey:users"`
  chatid      int    `json:"chatid" gorm:"index"`
  createdat   int64  `json:"createdat" gorm:"autocreatetime"`
  messagetype int    `json:"messagetype"` // 0 representing text , 1 representing image
  image       string `json:"image"`       // will be empty if the image doesn't contain image
}

我的用户结构;

type user struct {
  id                 int    `gorm:"primarykey;auto_increment"`
  username           string `gorm:"not null"`
  mail               string `gorm:"not null"`
  password           string `gorm:"not null"`
  updated            int64  `gorm:"autoupdatetime:milli"`
  created            int64  `gorm:"autocreatetime"`
  registermethod     string `gorm:"not null"`
  isemailvalidated   bool   `gorm:"default:false"`
  isonboardcompleted bool   `gorm:"default:false"`
}

这是我的查询;

messages := []model.message{}
err := r.db.joins("inner join users on messages.sender = users.id").where("chat_id = ?", chatid).order("created_at desc").limit(10).find(&messages).error

这是结果;

{
    "id": 1,
    "message": "csacsacsa",
    "sender": 16,
    "chatid": 0,
    "createdat": 0,
    "messagetype": 0,
    "image": ""
},

我想要实现的是,使用“发送者”部分加入用户对象,例如

{
        "id": 1,
        "message": "csacsacsa",
        "sender": {
          "id":16,
          "username": "bla bla bla",
          "mail": "bla bla bla" 
          ....
        },
        "chatid": 0,
        "createdat": 0,
        "messagetype": 0,
        "image": ""
},

正确答案


您需要向 message 结构添加一个字段,以便获取发件人的所有信息。

消息结构更改:

type message struct {
  id          int    `json:"id" gorm:"primarykey;auto_increment"`
  message     string `json:"message"`
  sender      int    `json:"senderid" gorm:"foreignkey:users"`
  senderobj   user   `json:"sender" gorm:"foreignkey:id;references:sender"`
  chatid      int    `json:"chatid" gorm:"index"`
  createdat   int64  `json:"createdat" gorm:"autocreatetime"`
  messagetype int    `json:"messagetype"` 
  image       string `json:"image"`       
}

这样,您就可以使用 preload 函数加载 senderobj 字段。

messages := []model.Message{}
err := r.db.Preload("SenderObj").Where("chat_id = ?", chatid).Order("created_at desc").Limit(10).Find(&messages).Error

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《如何正确进行gorm/go中的表连接操作?》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>