douhuang7263 2019-07-28 21:33 采纳率: 100%
浏览 239
已采纳

无法在GORM中设置“多对多”关联

I'm trying to set up an association between Users and PredictionsBags. My problem is that everything works OK if I use GORM's assumed names for referring objects, but I'd like to change the names a bit.

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
}

Every user, of course, owns zero or more 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
}

And I'd like to have .Related() work in the usual way:

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
}

My problem is that I can't find a way to change PredictionsBag.UserID to anything else and still have GORM figure out the relationships involved. I've been reading http://gorm.io/docs/has_many.html#Foreign-Key and if I change the relevant lines to

type User struct {
    // …
    Bags []PredictionsBag `gorm:"foreignkey:OwnerID"`
}

and

type PredictionsBag struct {
    // …
    OwnerID uint
    // …
}

I get this error:

[2019-07-28 14:23:49]  invalid association [] 

What am I doing wrong? I've also been reading http://gorm.io/docs/belongs_to.html, but I'm not sure which page to follow more closely.

  • 写回答

1条回答 默认 最新

  • doucan8246326 2019-07-29 20:55
    关注

    I'll have to Check Related() when I get home, but I think what you're looking for is Preload() This is my example that works with what you want.

    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
    }
    
    

    Using this might work with related, but I'm not sure what else needs to be changed:

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

    Update:

    I can get the Related() method to work, if you state the ForeignKey like the following:

        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
        }
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求解,我这个代码为什么运行不了
  • ¥15 remotes安装提示没有description文件
  • ¥15 AttributeError: 'NoneType' object has no attribute 'drop_duplicates'报错
  • ¥15 以下代码,运行结果报错
  • ¥15 Vivado仿真数据出错
  • ¥15 银河麒麟不支持vant等前端框架怎么办?
  • ¥15 vue3的子组件在父页面调用不显示不生效问题
  • ¥15 cadence PEX
  • ¥15 phython创建了文件 显示在项目下面,但运行不了,运行时还是运行main文件,并且说main文件不允许并行运行
  • ¥15 FutureWarning:不推荐使用空或全 NA 条目的 DataFrame 串联行为。怎么改呢?