Home > Article > Backend Development > How to create an association only if it doesn't exist? (gorm)
php editor Strawberry will explain to you how to create an association when the association does not exist. In programming, we often need to use associative arrays to store and manipulate data. But sometimes we need to create a new association in the associative array, but we don't want to overwrite the existing association. At this time, we can use conditional judgment to achieve this, and only create a new association when the association does not exist. This method can ensure the integrity and accuracy of data and improve the readability and maintainability of code. Let's take a look at the specific implementation method.
I am looping through an array of strings to create a document with that attribute (only if the attribute does not exist):
(dbi: my gorm database instance)
var posttags []models.tag for _, tagslug := range tagsarray { tag := models.tag{ slug: tagslug, } err = dbi.where("slug = ?", tagslug).firstorcreate(&tag).error if err != nil { return c.status(fiber.statusinternalservererror).json(fiber.map{ "error": "internal server error", }) } posttags = append(posttags, tag) }
Then create a post using these tags:
post := models.post{ ..., tags: posttags }] dbi.create(&post)
model:
type Post struct { BaseModel Title string `json:"title"` MarkdownUploadURL string `json:"markdownUploadUrl"` AuthorID string `json:"authorId"` Tags []Tag `json:"tags" gorm:"many2many:posts_tags"` } type Tag struct { BaseModel Slug string `json:"slug"` }
I tried: changing dbi.firstorcreate()
to dbi.first()
and then checking errors.is(err, gorm.errrecordnotfound
But every time I call the function, I get different tags with different ids, even though they already exist in the database...
Fixed . Instead of adding a tag to the post, like this:
post := models.post{ tags: posttags, } dbi.create(&post)
This is what I did:
post := models.Post { // Other fields (AuthorID, MarkdownUploadURL, Title) } dbi.Create(&post) dbi.Model(&post).Omit("Tags.*").Association("Tags").Append(postTags)
Reference: https://github.com/go-gorm/gorm/issues /3605
The above is the detailed content of How to create an association only if it doesn't exist? (gorm). For more information, please follow other related articles on the PHP Chinese website!