Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.1k views
in Technique[技术] by (71.8m points)

beego models struct 如何设置默认值?

以下代码中,struct里 我需要做插入操作时,CreateAt 这个字段想让以数据库默认值的方式写入 如何设置?


import (
    "fmt"
    "github.com/astaxie/beego/orm"
)

type ProjectUsers struct {
    Id int
    ProjectId int
    UserId int
    Amount float64
    StartedAt string
    EarningAmount float64
    Status int
    BtcEarning float64
    CreateAt string
}

func init() {
    orm.RegisterModel(new(ProjectUsers))
}

// 写入
func InsertOrder(projectId,userId int,availableHours string, money float64) (int64, bool) {
    o := orm.NewOrm()
    var data ProjectUsers
    data.ProjectId = projectId
    data.UserId = userId
    data.Amount = money
    data.StartedAt = availableHours
    resId,err := o.Insert(&data)
    fmt.Println(err)
    if err == nil && resId > 0{
        return resId,true
    }

    return 0,false
}```

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

new一个带默认值的对象就好了,不需要反射来实现。

func InsertOrder(projectId,userId int,availableHours string, money float64) (int64, bool) {
    o := orm.NewOrm()
    data := NewProjectUsers
    ...
}

func NewProjectUsers() ProjectUsers {
    return ProjectUsers{
        Status:   100,
        CreateAt: time.Now().String(),
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...