dongzhi8487 2019-08-06 15:28
浏览 14

FirstOrCreate with Asosciations无法正常工作

I've been playing with GORM as a newbie and having issues with FirstOrCreate(). I can't figure out how to handle calling it with an association, and SO answers and Googling haven't helped much. Below I have a sample program I've been playing with just to try to learn about how GORM works. I've tried several methods for passing in an artist or artist ID but nothing has worked.

I've tried: * Setting the ArtistID rather than the AlbumArtist field, * Renaming AlbumArtist to Artist to see if the reflection is getting confused * Finding the artist in the DB first and using the returned struct as the AlbumArtist in the FirstOrCreate query * Several permutations of Where clauses and Joins, but I really want to avoid the Joins() function if I can and let the ORM handle that until it becomes a performance issue

The output is below, and if you look at it you'll see that the artist is created fine. The worst test was setting the ArtistID directly - the record was inserted with the proper ID according to the Debug() SQL output, but the returned Album structs still had both AlbumArtist and ArtistID unset.

What is the proper way to do a lookup with an association in GORM?

package main

import (
    "fmt"

    "github.com/jinzhu/gorm"
    // Import the sqlite driver for GORM
    _ "github.com/jinzhu/gorm/dialects/sqlite"
)

type Artist struct {
    gorm.Model
    Name string
}

type Album struct {
    gorm.Model
    ArtistID    uint `gorm:"index:idx_artistid"`
    AlbumArtist Artist
    Name        string
    Songs       []Song
    Cover       Cover
}

type Cover struct {
    gorm.Model
    AlbumID     uint `gorm:"index:idx_albumid"`
    PictureData []byte
    MIMEType    string
}

type Song struct {
    gorm.Model
    AlbumID     uint     `gorm:"index:idx_artistid_albumid"`
    Artists     []Artist `gorm:"many2many:artist_songs;"`
    Title       string
    TrackNumber uint
    DiscNumber  uint
    Year        uint
    Duration    uint
    BitRate     uint
    Genre       string
    Type        string
    Filename    string
}

func NewDB(path string) (*gorm.DB, error) {
    db, err := gorm.Open("sqlite3", path)
    if err != nil {
        return nil, fmt.Errorf("Failed to connect to database: %v", err)
    }
    db.AutoMigrate(&User{}, &Artist{}, &Album{}, &Cover{}, &Song{})

    return db, nil
}

func GetArtist(db *gorm.DB, name string) *Artist {
    artist := &Artist{}
    db.Debug().FirstOrCreate(artist, &Artist{Name: name})
    return artist
}

func GetAlbum(db *gorm.DB, name string, artist string) *Album {
    album := &Album{Name: name, AlbumArtist: Artist{Name: artist}}
    db.Debug().Preload("Artists").FirstOrCreate(album)
    return &Album{Name: name}
}

func main() {
    db, _ := NewDB(":memory:")
    defer db.Close()
    artist := GetArtist(db, "Iron Maiden")
    fmt.Println("ArtistID:", artist.ID)
    album1 := GetAlbum(db, "Number of the Beast", "Iron Maiden")
    album2 := GetAlbum(db, "Powerslave", "Iron Maiden")
    fmt.Printf("%#v
", album1)
    fmt.Printf("IDS: %d %d %d
", artist.ID, album1.ArtistID, album2.ArtistID)
    if album1.ArtistID == album2.ArtistID && album1.ArtistID == artist.ID {
        fmt.Println("It works!")
    } else {
        fmt.Println("It doesn't work!")
    }
}

I get this output:

(/home/duckpuppy/src/gorm_test/main.go:67) 
[2019-08-06 10:57:45]  [0.21ms]  SELECT * FROM "artists"  WHERE "artists"."deleted_at" IS NULL AND (("artists"."name" = 'Iron Maiden')) ORDER BY "artists"."id" ASC LIMIT 1  
[0 rows affected or returned ] 

(/home/duckpuppy/src/gorm_test/main.go:67) 
[2019-08-06 10:57:45]  [0.13ms]  INSERT  INTO "artists" ("created_at","updated_at","deleted_at","name") VALUES ('2019-08-06 10:57:45','2019-08-06 10:57:45',NULL,'Iron Maiden')  
[1 rows affected or returned ] 
ArtistID: 1

(/home/duckpuppy/src/gorm_test/main.go:73) 
[2019-08-06 10:57:45]  [0.16ms]  SELECT * FROM "albums"  WHERE "albums"."deleted_at" IS NULL ORDER BY "albums"."id" ASC LIMIT 1  
[0 rows affected or returned ] 

(/home/duckpuppy/src/gorm_test/main.go:73) 
[2019-08-06 10:57:45]  [0.12ms]  INSERT  INTO "albums" ("created_at","updated_at","deleted_at","artist_id","name") VALUES ('2019-08-06 10:57:45','2019-08-06 10:57:45',NULL,0,'Number of the Beast')  
[1 rows affected or returned ] 

(/home/duckpuppy/src/gorm_test/main.go:73) 
[2019-08-06 10:57:45]  [0.22ms]  SELECT * FROM "albums"  WHERE "albums"."deleted_at" IS NULL ORDER BY "albums"."id" ASC LIMIT 1  
[1 rows affected or returned ] 

(/home/duckpuppy/src/gorm_test/main.go:73) 
[2019-08-06 10:57:45]  can't preload field Artists for main.Album 
&main.Album{Model:gorm.Model{ID:0x0, CreatedAt:time.Time{wall:0x0, ext:0, loc:(*time.Location)(nil)}, UpdatedAt:time.Time{wall:0x0, ext:0, loc:(*time.Location)(nil)}, DeletedAt:(*time.Time)(nil)}, ArtistID:0x0, AlbumArtist:main.Artist{Model:gorm.Model{ID:0x0, CreatedAt:time.Time{wall:0x0, ext:0, loc:(*time.Location)(nil)}, UpdatedAt:time.Time{wall:0x0, ext:0, loc:(*time.Location)(nil)}, DeletedAt:(*time.Time)(nil)}, Name:""}, Name:"Number of the Beast", Songs:[]main.Song(nil), Cover:main.Cover{Model:gorm.Model{ID:0x0, CreatedAt:time.Time{wall:0x0, ext:0, loc:(*time.Location)(nil)}, UpdatedAt:time.Time{wall:0x0, ext:0, loc:(*time.Location)(nil)}, DeletedAt:(*time.Time)(nil)}, AlbumID:0x0, PictureData:[]uint8(nil), MIMEType:""}}
IDS: 1 0 0
It doesn't work!
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥100 支付宝网页转账系统不识别账号
    • ¥15 基于单片机的靶位控制系统
    • ¥15 AT89C51控制8位八段数码管显示时钟。
    • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
    • ¥15 下图接收小电路,谁知道原理
    • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
    • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
    • ¥15 手机接入宽带网线,如何释放宽带全部速度
    • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
    • ¥15 ETLCloud 处理json多层级问题