使用Gorm

时间:2015-06-17 16:20:41

标签: go go-gorm

当我尝试从播客中播放剧集时,我得到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)
}

1 个答案:

答案 0 :(得分: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_id为0,因此查询没有多大意义。

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

即可
db.NewRecord(podcast)
db.Create(&podcast)

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

log.Print(episodes)