美文网首页
golang orm 查询关联model数据

golang orm 查询关联model数据

作者: 東玖零 | 来源:发表于2022-09-21 14:04 被阅读0次

背景:多表联查,定义model的属性名和数据库表字段名有可能出现不相同,需要做映射赋值。

目前只用到查询,写入暂时没有实现。

定义的proto文件中的model片段,其中看单据编号DocNo.

type NormalData struct {
    state         protoimpl.MessageState
    sizeCache     protoimpl.SizeCache
    unknownFields protoimpl.UnknownFields

    // 单据编号
    DocNo string `protobuf:"bytes,1,opt,name=oaDocNo,proto3" json:"oaDocNo,omitempty"`
    // 提交时间
    CreateAt string `protobuf:"bytes,2,opt,name=createAt,proto3" json:"createAt,omitempty"`

}

定义的表model片段。

type UserModel struct {
    ID string
    CreateAt time.Time `gorm:"autoCreateTime"`
}

当我们希望查询时ID的值能映射DocNo上时,查询的关键其实是as关键字。

resp = &pb.NormalData{}
selectArray := []string{
    "user_model.id as DocNo",
    "......省略"
}
db := utils.GormDB.Model(&models.UserModel{})
db.Select(selectArray)
db.Joins("....省略")
db.Where("....省略")
....省略
err = db.Find(&resp).Error

相关文章

网友评论

      本文标题:golang orm 查询关联model数据

      本文链接:https://www.haomeiwen.com/subject/gxwbortx.html