2014-08-28 11:33:43 +04:00
|
|
|
package gorm_test
|
|
|
|
|
|
|
|
import "testing"
|
|
|
|
|
|
|
|
type BasePost struct {
|
2014-08-28 14:53:27 +04:00
|
|
|
Id int64
|
2014-08-28 11:33:43 +04:00
|
|
|
Title string
|
|
|
|
Url string
|
|
|
|
}
|
|
|
|
|
|
|
|
type HNPost struct {
|
2014-08-28 13:21:43 +04:00
|
|
|
BasePost `gorm:"embedded"`
|
|
|
|
Upvotes int32
|
2014-08-28 11:33:43 +04:00
|
|
|
}
|
|
|
|
|
|
|
|
type EngadgetPost struct {
|
2014-08-28 15:14:58 +04:00
|
|
|
BasePost BasePost `gorm:"embedded"`
|
2014-08-28 11:33:43 +04:00
|
|
|
ImageUrl string
|
|
|
|
}
|
|
|
|
|
2014-08-28 13:21:43 +04:00
|
|
|
func TestSaveAndQueryEmbeddedStruct(t *testing.T) {
|
2014-08-28 15:14:58 +04:00
|
|
|
DB.Save(&HNPost{BasePost: BasePost{Title: "news"}})
|
2014-08-28 14:25:05 +04:00
|
|
|
DB.Save(&HNPost{BasePost: BasePost{Title: "hn_news"}})
|
2014-08-28 11:33:43 +04:00
|
|
|
var news HNPost
|
2014-08-28 13:21:43 +04:00
|
|
|
if err := DB.First(&news, "title = ?", "hn_news").Error; err != nil {
|
|
|
|
t.Errorf("no error should happen when query with embedded struct, but got %v", err)
|
|
|
|
} else {
|
2014-08-28 14:25:05 +04:00
|
|
|
if news.BasePost.Title != "hn_news" {
|
2014-08-28 13:21:43 +04:00
|
|
|
t.Errorf("embedded struct's value should be scanned correctly")
|
|
|
|
}
|
|
|
|
}
|
2014-08-28 15:14:58 +04:00
|
|
|
|
|
|
|
DB.Save(&EngadgetPost{BasePost: BasePost{Title: "engadget_news"}})
|
|
|
|
var egNews EngadgetPost
|
|
|
|
if err := DB.First(&egNews, "title = ?", "engadget_news").Error; err != nil {
|
|
|
|
t.Errorf("no error should happen when query with embedded struct, but got %v", err)
|
|
|
|
} else {
|
|
|
|
if egNews.BasePost.Title != "engadget_news" {
|
|
|
|
t.Errorf("embedded struct's value should be scanned correctly")
|
|
|
|
}
|
|
|
|
}
|
2014-08-28 11:33:43 +04:00
|
|
|
}
|