gorm - 定义默认值函数

问题描述 投票:0回答:2

我正在尝试按照 Gorm 的文档创建一个由函数定义的生成字段:

type Foo struct {
    ID            int64  `json:"id"`
    AmountOfBars  string `json:"amount_of_bars" gorm:"default:amount_of_bars()"`
}

type RelatedBar struct {
    FooId int64 `json:"foo_id"`
}

但是,我不明白在哪里以及如何定义 amount_of_bars,所以我将能够返回与RelatedBar相关的行的数量。

go go-gorm pq
2个回答
0
投票

您不在 Go 中定义这样的函数,而是通过

CREATE FUNCTION
在数据库中定义它。请参阅https://www.postgresql.org/docs/9.1/sql-createfunction.html


0
投票
type User struct {
ID        int    `json:"id" gorm:"autoIncrement; primaryKey"`
Username  string `json:"username" `
FirstName string `json:"first_name" `
LastName  string `json:"last_name" `
FullName  string `json:"full_name" `
Name      string `json:"name" `
AvatarURL string `json:"avatar_url" gorm:"default:'http://www.google/.com'" `

CreatedAt int // Set to current time if it is zero on creating
UpdatedAt int // Set to current unix seconds on updating or if it is zero on creating
Deleted   gorm.DeletedAt

}

© www.soinside.com 2019 - 2024. All rights reserved.