如何添加关系数据
时间:2024-04-15
浏览:246
作者:佚名
本篇文章向大家介绍《如何添加关系数据》,主要包括,具有一定的参考价值,需要的朋友可以参考一下。
问题内容
我开始通过 https://github.com/dejavuzhou/felix 的示例项目学习 golang
我的第一个项目已经运行良好。但我想要一些自定义输出。我的意思是,当我获取订单数据时,我想获取关系数据has many,但失败了。
从我的简单案例开始,我有 2 个表(order 和 detail_order)。一份订单有一个或多个detail_order。
我的handler_order.go
package handlers
import (
"github.com/berthojoris/ginbro/models"
"github.com/gin-gonic/gin"
)
func init() {
groupapi.get("order", orderall)
groupapi.get("order/:id", orderone)
groupapi.post("order", ordercreate)
groupapi.patch("order", orderupdate)
groupapi.delete("order/:id", orderdelete)
}
//all
func orderall(c *gin.context) {
mdl := models.order{}
query := &models.paginationquery{}
err := c.shouldbindquery(query)
if handleerror(c, err) {
return
}
list, total, err := mdl.all(query)
if handleerror(c, err) {
return
}
jsonpagination(c, list, total, query)
}
//one
func orderone(c *gin.context) {
var mdl models.order
id, err := parseparamid(c)
if handleerror(c, err) {
return
}
mdl.id = id
data, err := mdl.one()
if handleerror(c, err) {
return
}
jsondata(c, data)
}
//create
func ordercreate(c *gin.context) {
var mdl models.order
err := c.shouldbind(&mdl)
if handleerror(c, err) {
return
}
err = mdl.create()
if handleerror(c, err) {
return
}
jsondata(c, mdl)
}
//update
func orderupdate(c *gin.context) {
var mdl models.order
err := c.shouldbind(&mdl)
if handleerror(c, err) {
return
}
err = mdl.update()
if handleerror(c, err) {
return
}
jsonsuccess(c)
}
//delete
func orderdelete(c *gin.context) {
var mdl models.order
id, err := parseparamid(c)
if handleerror(c, err) {
return
}
mdl.id = id
err = mdl.delete()
if handleerror(c, err) {
return
}
jsonsuccess(c)
}
我的 model_order.go
package models
import (
"errors"
"time"
)
var _ = time.thursday
//order
type order struct {
id uint `gorm:"column:id" form:"id" json:"id" comment:"" sql:"int(10),pri"`
total float64 `gorm:"column:total" form:"total" json:"total" comment:"" sql:"double"`
orderdetail []orderdetail `gorm:"foreignkey:orderid" json:"detail_order"`
}
//tablename
func (m *order) tablename() string {
return "order"
}
//one
func (m *order) one() (one *order, err error) {
one = &order{}
err = crudone(m, one)
return
}
//all
func (m *order) all(q *paginationquery) (list *[]order, total uint, err error) {
list = &[]order{}
total, err = crudall(m, q, list)
return
}
//update
func (m *order) update() (err error) {
where := order{id: m.id}
m.id = 0
return crudupdate(m, where)
}
//create
func (m *order) create() (err error) {
m.id = 0
return mysqldb.create(m).error
}
//delete
func (m *order) delete() (err error) {
if m.id == 0 {
return errors.new("resource must not be zero value")
}
return cruddelete(m)
}
我的 model_order_detail.go
package models
import (
"errors"
"time"
)
var _ = time.thursday
//orderdetail
type orderdetail struct {
id uint `gorm:"column:id" form:"id" json:"id" comment:"" sql:"int(10),pri"`
orderid int `gorm:"column:order_id" form:"order_id" json:"order_id" comment:"" sql:"int(10),mul"`
itemid int `gorm:"column:item_id" form:"item_id" json:"item_id" comment:"" sql:"int(10)"`
itemname string `gorm:"column:item_name" form:"item_name" json:"item_name" comment:"" sql:"varchar(100)"`
itemprice float64 `gorm:"column:item_price" form:"item_price" json:"item_price" comment:"" sql:"double"`
}
//tablename
func (m *orderdetail) tablename() string {
return "order_detail"
}
//one
func (m *orderdetail) one() (one *orderdetail, err error) {
one = &orderdetail{}
err = crudone(m, one)
return
}
//all
func (m *orderdetail) all(q *paginationquery) (list *[]orderdetail, total uint, err error) {
list = &[]orderdetail{}
total, err = crudall(m, q, list)
return
}
//update
func (m *orderdetail) update() (err error) {
where := orderdetail{id: m.id}
m.id = 0
return crudupdate(m, where)
}
//create
func (m *orderdetail) create() (err error) {
m.id = 0
return mysqldb.create(m).error
}
//delete
func (m *orderdetail) delete() (err error) {
if m.id == 0 {
return errors.new("resource must not be zero value")
}
return cruddelete(m)
}
还有我的 db_helper.go
package models
import (
"errors"
"fmt"
"github.com/jinzhu/gorm"
"reflect"
"strconv"
"strings"
)
//paginationquery gin handler query binding struct
type paginationquery struct {
where string `form:"where"`
fields string `form:"fields"`
order string `form:"order"`
offset uint `form:"offset"`
limit uint `form:"limit"`
}
//string to string
func (pq *paginationquery) string() string {
return fmt.sprintf("w=%v_f=%s_o=%s_of=%d_l=%d", pq.where, pq.fields, pq.order, pq.offset, pq.limit)
}
func crudall(m interface{}, q *paginationquery, list interface{}) (total uint, err error) {
var tx *gorm.db
total, tx = getresourcecount(m, q)
if q.fields != "" {
columns := strings.split(q.fields, ",")
if len(columns) > 0 {
tx = tx.select(q.fields)
}
}
if q.order != "" {
tx = tx.order(q.order)
}
if q.offset > 0 {
tx = tx.offset(q.offset)
}
if q.limit <= 0 {
q.limit = 15
}
err = tx.limit(q.limit).find(list).error
return
}
func crudone(m interface{}, one interface{}) (err error) {
if mysqldb.where(m).first(one).recordnotfound() {
return errors.new("resource is not found")
}
return nil
}
func crudupdate(m interface{}, where interface{}) (err error) {
db := mysqldb.model(where).updates(m)
if err = db.error; err != nil {
return
}
if db.rowsaffected != 1 {
return errors.new("id is invalid and resource is not found")
}
return nil
}
func cruddelete(m interface{}) (err error) {
//warning when delete a record, you need to ensure it’s primary field has value, and gorm will use the primary key to delete the record, if primary field’s blank, gorm will delete all records for the model
//primary key must be not zero value
db := mysqldb.delete(m)
if err = db.error; err != nil {
return
}
if db.rowsaffected != 1 {
return errors.new("resource is not found to destroy")
}
return nil
}
func getresourcecount(m interface{}, q *paginationquery) (uint, *gorm.db) {
var tx = mysqldb.model(m)
conditions := strings.split(q.where, ",")
for _, val := range conditions {
w := strings.splitn(val, ":", 2)
if len(w) == 2 {
bindkey, bindvalue := w[0], w[1]
if intv, err := strconv.parseint(bindvalue, 10, 64); err == nil {
// bind value is int
field := fmt.sprintf("`%s` > ?", bindkey)
tx = tx.where(field, intv)
} else if fv, err := strconv.parsefloat(bindvalue, 64); err == nil {
// bind value is float
field := fmt.sprintf("`%s` > ?", bindkey)
tx = tx.where(field, fv)
} else if bindvalue != "" {
// bind value is string
field := fmt.sprintf("`%s` like ?", bindkey)
sv := fmt.sprintf("%%%s%%", bindvalue)
tx = tx.where(field, sv)
}
}
}
modelname := gettype(m)
rkey := redisprefix + modelname + q.string() + "_count"
v, err := mem.getuint(rkey)
if err != nil {
var count uint
tx.count(&count)
mem.set(rkey, count)
return count, tx
}
return v, tx
}
func gettype(v interface{}) string {
t := reflect.typeof(v)
if t.kind() == reflect.ptr {
return "*" + t.elem().name()
}
return t.name()
}
在我的订单模型中,我添加
OrderDetail []OrderDetail `gorm:"foreignkey:OrderID" json:"detail_order"`
对于我的关系数据。结果是
即使我有关系数据
我的问题,如何在 order struct 中添加/附加 orderdetail struct 以便我的表关系数据出来。
谢谢
解决方案
您需要在查询中添加 Preload 调用,或者在获取对象后添加 Related 调用。使用方法见the Preload docs here或the Related docs。如果您使用 Preload(为了简单起见,我建议您使用 Preload),您可能必须放弃 crudeOne 函数或对其进行调整以满足您的需求。
理论要掌握,实操不能落!以上关于《如何添加关系数据》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.20
11.20
11.20
11.20
热门专题
