【问题标题】:Trouble retrieving Has Many using Gorm使用 Gorm 检索有很多问题
【发布时间】:2015-09-03 00:22:15
【问题描述】:

当我尝试从播客中取回剧集时,我收到 invalid association []。不知道我做错了什么。

package main

import (
    "log"

    "github.com/jinzhu/gorm"
    _ "github.com/mattn/go-sqlite3"
)

type Podcast struct {
    Id       int
    Title    string
    RssUrl   string `sql:"unique_index"`
    Url      string
    Episodes []Episode
}

type Episode struct {
    Id         int
    PodcastID  int `sql:"index"`
    Title      string
    Url        string `sql:"unique_index"`
    Downloaded bool
}

func main() {
    db, err := gorm.Open("sqlite3", "gorm.db")
    if err != nil {
        log.Fatal(err)
    }
    db.LogMode(true)

    db.CreateTable(&Podcast{})
    db.CreateTable(&Episode{})

    podcast := Podcast{
      Title:    "My Podcast",
      RssUrl:   "http://example.com/feed/",
      Url:      "http://www.example.com",
      Episodes: []Episode{{Title: "Episode One Point Oh!", Url: "http://www.example.com/one-point-oh", Downloaded: false}},
    }

    var episodes []Episode
    db.Model(&podcast).Related(&episodes)
}

【问题讨论】:

    标签: go go-gorm


    【解决方案1】:

    您使用的是哪个版本的 GO 和 GORM?我在我的机器上试过了,这是日志:

    [2015-06-17 19:02:11]  [12.00ms]  CREATE TABLE "podcasts" ("id" integer,"title" varchar(255),"rss_url" varchar(255),"url" varchar(255) , PRIMARY KEY ("id"))
    [2015-06-17 19:02:11]  [1.26ms]  CREATE TABLE "episodes" ("id" integer,"podcast_id" integer,"title" varchar(255),"url" varchar(255),"downloaded" bool , PRIMARY KEY ("id")) 
    [2015-06-17 19:02:11]  [1.25ms]  SELECT  * FROM "episodes"  WHERE ("podcast_id" = '0')
    

    请注意,由于您没有创建 podcast 变量,因此 podcast_id 为 0,因此查询没有多大意义。

    要创建播客,只需添加此代码

    db.NewRecord(podcast)
    db.Create(&podcast)
    
    var episodes []Episode
    db.Model(&podcast).Related(&episodes)
    
    log.Print(episodes)
    

    【讨论】:

    • 我的 gorm 版本真的过时了。我一定以前跑过它,它在我不知道的情况下一直坐在那里陈旧。你能给我一个如何创建播客变量的代码示例吗?谢谢!
    • 虽然上面仍然搜索 podcast_id = 0?
    • 否,因为播客 id 在插入后由 gorm 填充;)
    • (/home/gregf/code/go/src/github.com/gregf/gormtest/main.go:48) [2015-06-17 15:28:58] [0.55ms] SELECT * FROM "episodes" WHERE ("podcast_id" = '0
    • 在我的机器上一切正常,您检查是否发生任何错误? Create 方法有一个 .Error 属性,例如
    猜你喜欢
    • 1970-01-01
    • 2011-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-27
    • 2021-10-27
    相关资源
    最近更新 更多