php小編草莓將為您解答如何在關(guān)聯(lián)不存在時(shí)創(chuàng)建關(guān)聯(lián)。在編程中,我們經(jīng)常需要使用關(guān)聯(lián)數(shù)組來(lái)存儲(chǔ)和操作數(shù)據(jù)。但有時(shí)候我們需要在關(guān)聯(lián)數(shù)組中創(chuàng)建一個(gè)新的關(guān)聯(lián),但又不希望覆蓋已存在的關(guān)聯(lián)。這時(shí),我們可以使用條件判斷來(lái)實(shí)現(xiàn),只在關(guān)聯(lián)不存在時(shí)才創(chuàng)建新的關(guān)聯(lián)。這種方法可以保證數(shù)據(jù)的完整性和準(zhǔn)確性,提高代碼的可讀性和可維護(hù)性。下面我們來(lái)看具體的實(shí)現(xiàn)方法。
問(wèn)題內(nèi)容
我正在循環(huán)遍歷字符串?dāng)?shù)組,以創(chuàng)建具有該屬性的文檔(僅當(dāng)該屬性不存在時(shí)):
(dbi:我的 gorm 數(shù)據(jù)庫(kù)實(shí)例)
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) }
登錄后復(fù)制
然后使用這些標(biāo)簽創(chuàng)建帖子:
post := models.post{ ..., tags: posttags }] dbi.create(&post)
登錄后復(fù)制
型號(hào):
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"` }
登錄后復(fù)制
我嘗試:將 dbi.firstorcreate()
更改為 dbi.first()
,然后檢查 errors.is(err, gorm.errrecordnotfound
但是每次調(diào)用該函數(shù)時(shí),我都會(huì)得到具有不同 id 的不同標(biāo)簽,即使它們已經(jīng)存在于數(shù)據(jù)庫(kù)中……
解決方法
已修復(fù)。而不是在帖子中添加標(biāo)簽,如下所示:
post := models.post{ tags: posttags, } dbi.create(&post)
登錄后復(fù)制
我是這樣做的:
post := models.Post { // Other fields (AuthorID, MarkdownUploadURL, Title) } dbi.Create(&post) dbi.Model(&post).Omit("Tags.*").Association("Tags").Append(postTags)
登錄后復(fù)制
參考:https://github.com/go-gorm/gorm/issues /3605