为了账号安全,请及时绑定邮箱和手机立即绑定

无法在 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条经验 获得超7个赞

我回家后必须检查一下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:"dave@example.com"}

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

    DB.Create(&user)

}


func main()  {


    user := User{Email:"dave@example.com"}

    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 关注
  • 68 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信