Reputation: 11
I am trying to add array data type using 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??
Upvotes: 0
Views: 4315
Reputation: 11807
Has mpromonet
stated that you are replacing tag but not appending on the existing tags.
Here how you can modify your existing Update statement to make it work
Tags pq.StringArray `gorm:"type:text[]" json:"tags"`
array_cat
functiont.DB.Model(&database.Token{})
.Where("address = ?", address)
.Update("tags", gorm.Expr("array_cat(tags, ?)", pq.Array([]string{"3","4"})))
||
operatort.DB.Model(&database.Token{})
.Where("address = ?", address)
.Update("tags", gorm.Expr("tags || ?", pq.Array([]string{"3","4"})))
Upvotes: 2
Reputation: 11963
Your code doesnot append, it replace the Tags
field with ["1","2"]
.
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)
Upvotes: 1