jjzjj

go - 无法在 GORM 中设置 has-many 关联

coder 2024-07-08 原文

我正在尝试在 UserPredictionsBag 之间建立关联。我的问题是,如果我使用 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
}

当然,每个用户都拥有零个或多个 PredictionsBag:

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 ,但我不确定应该更密切地关注哪个页面。

最佳答案

我到家后必须检查 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"`

更新:

如果您像下面这样声明 ForeignKey,我可以让 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
    }

关于go - 无法在 GORM 中设置 has-many 关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57245129/

有关go - 无法在 GORM 中设置 has-many 关联的更多相关文章

  1. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  2. ruby - capybara field.has_css?匹配器 - 2

    我在MiniTest::Spec和Capybara中使用以下规范:find_field('Email').must_have_css('[autofocus]')检查名为“电子邮件”的字段是否具有autofocus属性。doc说如下:has_css?(path,options={})ChecksifagivenCSSselectorisonthepageorcurrentnode.据我了解,字段“Email”是一个节点,因此调用must_have_css绝对有效!我做错了什么? 最佳答案 通过JonasNicklas得到了答案:No

  3. ruby-on-rails - 无法使用 Rails 3.2 创建插件? - 2

    我对最新版本的Rails有疑问。我创建了一个新应用程序(railsnewMyProject),但我没有脚本/生成,只有脚本/rails,当我输入ruby./script/railsgeneratepluginmy_plugin"Couldnotfindgeneratorplugin.".你知道如何生成插件模板吗?没有这个命令可以创建插件吗?PS:我正在使用Rails3.2.1和ruby​​1.8.7[universal-darwin11.0] 最佳答案 随着Rails3.2.0的发布,插件生成器已经被移除。查看变更日志here.现在

  4. ruby - 无法运行 Rails 2.x 应用程序 - 2

    我尝试运行2.x应用程序。我使用rvm并为此应用程序设置其他版本的ruby​​:$rvmuseree-1.8.7-head我尝试运行服务器,然后出现很多错误:$script/serverNOTE:Gem.source_indexisdeprecated,useSpecification.Itwillberemovedonorafter2011-11-01.Gem.source_indexcalledfrom/Users/serg/rails_projects_terminal/work_proj/spohelp/config/../vendor/rails/railties/lib/r

  5. ruby-on-rails - 无法在centos上安装therubyracer(V8和GCC出错) - 2

    我正在尝试在我的centos服务器上安装therubyracer,但遇到了麻烦。$geminstalltherubyracerBuildingnativeextensions.Thiscouldtakeawhile...ERROR:Errorinstallingtherubyracer:ERROR:Failedtobuildgemnativeextension./usr/local/rvm/rubies/ruby-1.9.3-p125/bin/rubyextconf.rbcheckingformain()in-lpthread...yescheckingforv8.h...no***e

  6. ruby - 续集在添加关联时访问many_to_many连接表 - 2

    我正在使用Sequel构建一个愿望list系统。我有一个wishlists和itemstable和一个items_wishlists连接表(该名称是续集选择的名称)。items_wishlists表还有一个用于facebookid的额外列(因此我可以存储opengraph操作),这是一个NOTNULL列。我还有Wishlist和Item具有续集many_to_many关联的模型已建立。Wishlist类也有:selectmany_to_many关联的选项设置为select:[:items.*,:items_wishlists__facebook_action_id].有没有一种方法可以

  7. ruby - 无法让 RSpec 工作—— 'require' : cannot load such file - 2

    我花了三天的时间用头撞墙,试图弄清楚为什么简单的“rake”不能通过我的规范文件。如果您遇到这种情况:任何文件夹路径中都不要有空格!。严重地。事实上,从现在开始,您命名的任何内容都没有空格。这是我的控制台输出:(在/Users/*****/Desktop/LearningRuby/learn_ruby)$rake/Users/*******/Desktop/LearningRuby/learn_ruby/00_hello/hello_spec.rb:116:in`require':cannotloadsuchfile--hello(LoadError) 最佳

  8. ruby - 无法覆盖 irb 中的 to_s - 2

    我在pry中定义了一个函数:to_s,但我无法调用它。这个方法去哪里了,怎么调用?pry(main)>defto_spry(main)*'hello'pry(main)*endpry(main)>to_s=>"main"我的ruby版本是2.1.2看了一些答案和搜索后,我认为我得到了正确的答案:这个方法用在什么地方?在irb或pry中定义方法时,会转到Object.instance_methods[1]pry(main)>defto_s[1]pry(main)*'hello'[1]pry(main)*end=>:to_s[2]pry(main)>defhello[2]pry(main)

  9. ruby - 无法在 60 秒内获得稳定的 Firefox 连接 (127.0.0.1 :7055) - 2

    我使用的是Firefox版本36.0.1和Selenium-Webdrivergem版本2.45.0。我能够创建Firefox实例,但无法使用脚本继续进行进一步的操作无法在60秒内获得稳定的Firefox连接(127.0.0.1:7055)错误。有人能帮帮我吗? 最佳答案 我遇到了同样的问题。降级到firefoxv33后一切正常。您可以找到旧版本here 关于ruby-无法在60秒内获得稳定的Firefox连接(127.0.0.1:7055),我们在StackOverflow上找到一个类

  10. ruby - 安装 Ruby 时遇到问题(无法下载资源 "readline--patch") - 2

    当我尝试安装Ruby时遇到此错误。我试过查看this和this但无济于事➜~brewinstallrubyWarning:YouareusingOSX10.12.Wedonotprovidesupportforthispre-releaseversion.Youmayencounterbuildfailuresorotherbreakages.Pleasecreatepull-requestsinsteadoffilingissues.==>Installingdependenciesforruby:readline,libyaml,makedepend==>Installingrub

随机推荐