Your Question
I have a Polymorphism Association described as follow:
type UserTypeA struct {
Id uint64 `json:"-"`
Firstname string `json:"firstname" gorm:"size:255;not null"`
Lastname string `json:"lastname" gorm:"size:255;not null"`
Message []Message `json:"-" gorm:"polymorphic:User;polymorphicValue:UserTypeA"`
}
type UserTypeB struct {
Id uint64 `json:"-"`
Firstname string `json:"firstname" gorm:"size:255;not null"`
Lastname string `json:"lastname" gorm:"size:255;not null"`
Message []Message `json:"-" gorm:"polymorphic:User;polymorphicValue:UserTypeB"`
}
type Message struct {
Id uint64 `json:"-"`
UserID uint64 `json:"userId" gorm:"not null"`
UserType string `json:"userType" gorm:"size:255;not null"`
Message string `json:"message" gorm:"type:text;not null"`
}
Now I want to fetch all Messages and want to have the user in the json response in it. Is this possible in gorm? So far I tried the following:
var messages []Message
DB.Preload("UserTypeB").Find(&messages, Message{})
The relation "UserTypeB" can not be found. How can I get the following output? Is there another way to get the wanted result?
{
"message": "Lorem ipsum...",
"user": { // Gorm should either select UserTypeA or UserTypeB automatically by column "UserType"
"id": 1234,
"firstname": "John",
"Lastname": "Doe"
}
}
The document you expected this should be explained
https://gorm.io/docs/has_many.html#Polymorphism-Association
Expected answer
The documentation only describes how to create new entries. But the part of getting entries with polymorphism associations is still missing. I also searched on google & co. But I only found a solution when I would fetch UserTypeA or UserTypeB, but not Messages .
Comment From: github-actions[bot]
This issue has been automatically marked as stale because it has been open 360 days with no activity. Remove stale label or comment or this will be closed in 180 days
Comment From: timmyhoa
Any solution?
Comment From: Br3nda
does Preload of polymorphic work at all?
Comment From: nghiadanggeocomply
Any idea for this?
Comment From: duxphp
Unsolvable, feel free to try other orm or manual splicing
Comment From: alkawero
you can try with raw query like this
type MessageWithUser struct {
MessageID uint64
MessageContent string
UserType string
Firstname string
Lastname string
}
var messages []MessageWithUser
query := `
SELECT
messages.id AS message_id,
messages.message AS message_content,
messages.user_type,
CASE
WHEN messages.user_type = 'UserTypeA' THEN user_type_as.firstname
WHEN messages.user_type = 'UserTypeB' THEN user_type_bs.firstname
END as firstname,
CASE
WHEN messages.user_type = 'UserTypeA' THEN user_type_as.lastname
WHEN messages.user_type = 'UserTypeB' THEN user_type_bs.lastname
END as lastname
FROM messages
LEFT JOIN user_type_as ON messages.user_id = user_type_as.id AND messages.user_type = 'UserTypeA'
LEFT JOIN user_type_bs ON messages.user_id = user_type_bs.id AND messages.user_type = 'UserTypeB'
`
db.Raw(query).Scan(&messages)