如何在GORM中将PostgreSQL函数设置为默认值?

huangapple go评论71阅读模式
英文:

How to set a PostgreSQL function as default value in GORM?

问题

我想要类似这样的代码:

type User struct {
    ID          int     `sql:"default:<myfunction>"`
}

使用 GORM 可以实现这个吗?

英文:

I want something like:

type User struct {
    ID          int     `sql:&quot;default:&lt;myfunction&gt;&quot;`
}

Is this possible with GORM?

答案1

得分: 13

你试过了吗?你可以这样做:

time.Time `sql:"DEFAULT:current_timestamp"`

它将使用"current_timestamp"函数作为默认值。如果你想要默认值是字符串current_timestamp,你可以这样做:

time.Time `sql:"DEFAULT:'current_timestamp'"`

所以,简而言之,是可以的。你只需要这样做:

type User struct {
    ID          int     `sql:"DEFAULT:myfunction"`
}
英文:

Have you tried it? You can do

time.Time `sql:&quot;DEFAULT:current_timestamp&quot;`

and it will use the "current_timestamp" function. If you want the default to be the string current_timestamp, you would do

time.Time `sql:&quot;DEFAULT:&#39;current_timestamp&#39;&quot;`

So, in short, yes, it is possible. You would just do:

type User struct {
    ID          int     `sql:&quot;DEFAULT:myfunction&quot;`
}

huangapple
  • 本文由 发表于 2015年11月7日 02:27:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/33573306.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定