Featured image of post gormでbelongs to にハマった話

gormでbelongs to にハマった話

Twitter ツイート Hatena Bookmark ブックマーク

最近Golangを積極的に使っている僕ですが、Golangでwebアプリをいくつか作り始めました。
ORMはgormを使っているのですが、Belongs Toでハマりました。

ドキュメント通りを参考にBelongs toの設定をしてみました。
http://jinzhu.me/gorm/associations.html#belongs-to

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
type Article struct {
	ID uint
	Title string
	Descriptions string
	Author Author
	AuthorID int64 `gorm:"column:hoge_author_id"`
}

type Author struct {
	ID uint
	Username string
	DisplayName string
	Image string
	Description string
}

//...
db.Model(&article).Related(&author)

実行してみると(invalid association [])と言われてしまった・・・。

Relatedのコードを見てたらどうやらAuthorID ではなくAuthorIdにすればいい。
gorm/scope.go at eae7f6be603af3190e032fe3c4d465ddaf6ea3d4 · jinzhu/gorm · GitHub

もしくはRelated の二つ目の引数にdb.Model(&article).Related(&author,"Author")って感じで指定すればいい・・・。

ドキュメント通りに動かなくて辛い・・・。もしくは僕が勘違いしているだけ??? まだgolang始めたばかりで、いろいろと大変です。

comments powered by Disqus
Built with Hugo
テーマ StackJimmy によって設計されています。