How to create an association only if it doesn't exist? (gorm)

WBOY
Release: 2024-02-09 11:15:28
forward
923 people have browsed it

仅当关联不存在时如何创建关联? (戈尔姆)

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.

Question content

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)
}
Copy after login

Then create a post using these tags:

post := models.post{
       ...,
       tags: posttags 
}]

dbi.create(&post)
Copy after login

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"`
}
Copy after login

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

Workaround

Fixed . Instead of adding a tag to the post, like this:

post := models.post{
       tags: posttags, 
}

dbi.create(&post)
Copy after login

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)
Copy after login

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!

Related labels:
source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template