go - beego中如何编写有效的保存和更新功能?

标签 go beego

我在 BaseModel 中有以下功能,我可以在任何地方使用。

func (d *Dummy) Save() (int64, error) {
    o := orm.NewOrm()
    var err error
    var count int64
    if d.Id == 0 {
        count, err = o.Insert(d)
    } else {
        count, err = o.Update(d)
    }

    return count, err
}
我是这样使用的
d := models.Dummy{Id: 10}
d.SomeValue = "x"
d.Save()
问题是我有“d.OtherValue”已经在数据库中了。
执行此函数后,它会更新为 0。
由于它是对所有模型都有效的通用模型函数,我该如何解决这个问题?基本上,我想在单个查询中执行此操作,就像更新/保存 Django ORM

最佳答案

您需要先加载记录。您错过了 Read(&struct) ORM方法:

o := orm.NewOrm()
d := models.Dummy{Id: 10}

readErr:= o.Read(&d)

// check if the record with Id of 10 exists and update...
if readErr!= o.ErrNoRows {
    if rowsAffected, err := o.Update(&d); err == nil {
        // record updated (rowsAffected indicates the number of affected rows)
    }
} else {
    // record does not exist, create a new one
    id, insertErr:= o.Insert(&d)
    if insertErr== nil {
        // success
    }
}
     
然后你应该检查 ORM 是否找到了一条记录
更多详情可以引用ReadUpdate方法。

关于go - beego中如何编写有效的保存和更新功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64111834/

相关文章:

c++ - 用 go + swig 替换 c++

php - Go 和 PHP 中的 SHA256 给出不同的结果

go - 寻求有关如何在 Golang 中管理微服务的帮助

templates - 遍历模板中的对象数组 (Go)

api - beego api post插入数据

go - Beego POST方法始终寻找模板文件

string - 可以在Go中使用`string()`将字节转换为空字符串吗?

api - 如何追加或合并 2 []array golang beego

go - 如何在 golang 中调整数组以不随机化预定键?

mysql - 使用beego登录网站