亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

無法在 GORM 中建立多關聯

無法在 GORM 中建立多關聯

Go
白衣非少年 2023-07-10 10:57:37
User我正在嘗試在s 和s之間建立關聯PredictionsBag。我的問題是,如果我使用 GORM 的假定名稱來引用對象,一切都會正常,但我想稍微更改一下名稱。type User struct {    gorm.Model    //  We’ll try not using usernames for now    Email        string `gorm:"not null;unique_index"`    Password     string `gorm:"-"`    PasswordHash string `gorm:"not null"`    Remember     string `gorm:"-"` // A user’s remember token.    RememberHash string `gorm:"not null;unique_index"`    Bags []PredictionsBag}當然,每個用戶都擁有零個或多個PredictionsBags:type PredictionsBag struct {    gorm.Model    UserID uint // I want this to be "OwnerID"    Title        string    NotesPublic  string `gorm:"not null"` // Markdown field. May be published.    NotesPrivate string `gorm:"not null"` // Markdown field. Only for (private) viewing and export.    Predictions []Prediction}我想以.Related()通常的方式工作:func (ug *userGorm) ByEmail(email string) (*User, error) {    var ret User    matchingEmail := ug.db.Where("email = ?", email)    err := first(matchingEmail, &ret)    if err != nil {        return nil, err    }    var bags []PredictionsBag    if err := ug.db.Model(&ret).Related(&bags).Error; err != nil {        return nil, err    }    ret.Bags = bags    return &ret, nil}我的問題是,我無法找到一種方法來更改PredictionsBag.UserID為其他任何內容,并且仍然讓 GORM 弄清楚所涉及的關系。我一直在閱讀http://gorm.io/docs/has_many.html#Foreign-Key如果我將相關行更改為type User struct {    // …    Bags []PredictionsBag `gorm:"foreignkey:OwnerID"`}和type PredictionsBag struct {    // …    OwnerID uint    // …}我收到此錯誤:[2019-07-28 14:23:49]  invalid association [] 我究竟做錯了什么?我也一直在閱讀http://gorm.io/docs/belongs_to.html,但我不確定應該更密切地關注哪個頁面。
查看完整描述

1 回答

?
largeQ

TA貢獻2039條經驗 獲得超8個贊

我回家后必須檢查一下Related(),但我認為您正在尋找的是Preload()這是我的示例,可以滿足您的需求。


package main


import (

    "errors"

    "fmt"

    _ "github.com/go-sql-driver/mysql"

    "github.com/jinzhu/gorm"

    _ "github.com/jinzhu/gorm/dialects/mysql"

    "log"

)


var DB *gorm.DB


func init() {

    var err error


    DB, err = gorm.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s:3306)/%s?&parseTime=True&loc=Local", "root", "root", "localhost", "testing"))

    if err != nil {

        log.Fatal(err)

    }


    DB.DropTableIfExists(&User{}, &PredictionsBag{})

    DB.AutoMigrate(&User{}, &PredictionsBag{})

    user := User{Email:"[email protected]"}

    user.Bags = append(user.Bags, PredictionsBag{OwnerID: user.ID, NotesPrivate: "1", NotesPublic: "1"})

    DB.Create(&user)

}


func main()  {


    user := User{Email:"[email protected]"}

    err := user.ByEmail()

    if err != nil {

        log.Println(err)

    }

    fmt.Println(user.ID, user.Email, "Bags:", len(user.Bags))


    DB.Close()

}



type User struct {

    gorm.Model

    //  We’ll try not using usernames for now


    Email        string `gorm:"not null;unique_index"`

    Password     string `gorm:"-"`

    PasswordHash string `gorm:"not null"`

    Remember     string `gorm:"-"` // A user’s remember token.

    RememberHash string `gorm:"not null;unique_index"`


    Bags []PredictionsBag `gorm:"foreignkey:OwnerID"`

}


type PredictionsBag struct {

    gorm.Model

    OwnerID uint


    Title        string

    NotesPublic  string `gorm:"not null"` // Markdown field. May be published.

    NotesPrivate string `gorm:"not null"` // Markdown field. Only for (private) viewing and export.


}


func (ug *User) ByEmail() error {


    DB.Where("email = ?", ug.Email).Preload("Bags").Limit(1).Find(&ug)

    if ug.ID == 0 {

        return errors.New("no user found")

    }

    return nil

}


使用它可能適用于相關的,但我不確定還需要更改什么:


    Bags []PredictionsBag `gorm:"foreignkey:OwnerID;association_foreignkey:ID"`


更新:


Related()如果你像下面這樣聲明外鍵,我就可以讓該方法起作用:


    DB.Where("email = ?", ug.Email).Limit(1).Find(&ug)

    if ug.ID == 0 {

        return errors.New("no user found")

    }

    if err := DB.Model(&ug).Related(&ug.Bags, "owner_id").Error; err != nil {

        return err

    }


查看完整回答
反對 回復 2023-07-10
  • 1 回答
  • 0 關注
  • 134 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號