0

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??

0

2 Answers 2

2

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"})))
Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.