[英]How to append to the string array in gorm
I am trying to add array data type using gorm我正在尝试使用 gorm 添加数组数据类型
type Token struct {
Base
Tags pq.StringArray json:"tags"
}
using使用
t.DB.Model(&database.Token{}).Where("address = ?", address).Update(&database.Token{Tags: ["1","2"],})
But, I am unable to append a new tag to the data.但是,我无法向数据附加新标签。 It is getting replaced.. Any idea??它正在被取代......知道吗?
Your code doesnot append, it replace the Tags
field with ["1","2"]
.您的代码不会附加,而是用["1","2"]
替换Tags
字段。
In order to append new tags to existing one, you may proceed like :为了将新标签附加到现有标签,您可以执行以下操作:
// read row
t.DB.Model(&database.Token).Where("address = ?", address)
// append new tags
newTags := append(database.Token.Tags, "1", "2")
// update database
t.DB.Model(&database.Token).Update("tags", newTags)
Has mpromonet
stated that you are replacing tag but not appending on the existing tags. mpromonet
是否表示您正在替换标签但未附加到现有标签上。
Here how you can modify your existing Update statement to make it work在这里您可以如何修改现有的 Update 语句以使其工作
Tags pq.StringArray `gorm:"type:text[]" json:"tags"`
array_cat
function使用array_cat
函数t.DB.Model(&database.Token{})
.Where("address = ?", address)
.Update("tags", gorm.Expr("array_cat(tags, ?)", pq.Array([]string{"3","4"})))
||
与||
operator操作员t.DB.Model(&database.Token{})
.Where("address = ?", address)
.Update("tags", gorm.Expr("tags || ?", pq.Array([]string{"3","4"})))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.