Satya Kumar Itekela
Satya Kumar Itekela

Reputation: 11

How to append to the string array in gorm

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

Answers (2)

Chandan
Chandan

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

Update Token struct definition

Tags   pq.StringArray `gorm:"type:text[]" json:"tags"`

With array_cat function

t.DB.Model(&database.Token{})
  .Where("address = ?", address)
  .Update("tags", gorm.Expr("array_cat(tags, ?)", pq.Array([]string{"3","4"})))

With || operator

t.DB.Model(&database.Token{})
  .Where("address = ?", address)
  .Update("tags", gorm.Expr("tags || ?", pq.Array([]string{"3","4"})))

Upvotes: 2

mpromonet
mpromonet

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

Related Questions