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

无法在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 在codeblocks里主函数运行到打印生成的链表就结束了 没有再往下是为什么呢
  • ¥15 宇视vms-B200-A16@R启动不了,如下图所示,在软件工具搜不到,如何解决?(操作系统-linux)
  • ¥500 寻找一名电子工程师完成pcb主板设计(拒绝AI生成式答案)
  • ¥15 关于#mysql#的问题:UNION ALL(相关搜索:sql语句)
  • ¥15 matlab二位可视化能否针对不同数值范围分开分级?
  • ¥15 已经创建了模拟器但是不能用来运行app 怎么办😭自己搞两天了
  • ¥15 关于#极限编程#的问题,请各位专家解答!
  • ¥20 win11账户锁定时间设为0无法登录
  • ¥45 C#学生成绩管理系统
  • ¥30 matlab appdesigner私有函数嵌套整合