Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

GORM failing to guess relations for embedded types #3224

Closed
perelin opened this issue Aug 3, 2020 · 3 comments
Closed

GORM failing to guess relations for embedded types #3224

perelin opened this issue Aug 3, 2020 · 3 comments
Assignees

Comments

@perelin
Copy link

perelin commented Aug 3, 2020

GORM Playground Link

go-gorm/playground#62

Description

For some cases I need to extend my standard models with computed data. E.g. display information about the existence of some DB values in the UI. I do this by creating an extended model via type embedding like so:

/* Standard Models */

type User struct {
	gorm.Model
	Name      string
	Documents []*Document // has-many
}

type Document struct {
	gorm.Model
	User             *User // belongs-to
	UserID           uint
	Name             string
	DocumentFulltext *DocumentFulltext // has-one
}

type DocumentFulltext struct {
	gorm.Model
	Document   *Document // belongs-to
	DocumentID uint 
	Fulltext   string
}

/* Extensions */

type DocumentListEntry struct {
	Document       `gorm:"embedded"`
	FulltextExists bool
}

My query then looks like this:

queryConnection := DBConnection
queryConnection = queryConnection.Joins("left join document_fulltexts on documents.id = document_fulltexts.document_id")
queryConnection = queryConnection.Where(`"documents"."user_id" = ?`, userID)
queryConnection = queryConnection.Select(
	`"documents"."user_id",
	"documents"."name",
	CASE WHEN "document_fulltexts"."fulltext" IS NOT NULL THEN TRUE ELSE FALSE END AS "fulltext_exists"`,
)
documents := []DocumentListEntry{}
queryConnection.Table("documents").Scan(&documents)

This is the error I get:

[error] failed to guess DocumentFulltext's relations with DocumentListEntry's field DocumentFulltext 1 g false

How do I need to construct the extended model to make this work?

Is this approach recommended at all? Whats the best-practice here? Any alternatives I should consider?

Thx!

@jinzhu
Copy link
Member

jinzhu commented Aug 4, 2020

Fixed, thank you for your report.

@perelin
Copy link
Author

perelin commented Aug 4, 2020

Wow, that was quick! Will try out later :)

@perelin
Copy link
Author

perelin commented Aug 4, 2020

Works like a charm, thanks for the quick fix! Found the sponsoring links and will use them :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants