gorm / go如何正确地连接两个表格?

huangapple go评论95阅读模式
英文:

gorm / go how to join two tables properly?

问题

我的消息结构体:

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 表示文本,1 表示图片
    Image       string `json:"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": ""
}

我想要实现的目标是,通过使用 "sender" 部分来连接用户对象,如下所示:

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

My message struct ;

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
}

My user struct;

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"`
}

Here is my query ;

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

here is the outcome ;

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

what I want to achieve is, to join user object using "sender" section like

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

答案1

得分: 1

你需要在Message结构体中添加一个字段,以便存储发送者的所有信息。

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
英文:

You need to add a field to your Message struct in order to all information for the sender.

Message struct changes:

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"`       
}

With this, you can use the Preload function to load the SenderObj field.

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

huangapple
  • 本文由 发表于 2021年12月8日 00:42:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/70263860.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定