【发布时间】:2022-01-12 17:54:54
【问题描述】:
我的消息结构;
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": ""
},
【问题讨论】:
标签: postgresql go join go-gorm