go-gorm / gorm

The fantastic ORM library for Golang, aims to be developer friendly
https://gorm.io
MIT License
36.53k stars 3.91k forks source link

Preload / load Polymorphism Association #5591

Open tsdevelopment opened 2 years ago

tsdevelopment commented 2 years ago

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 .

github-actions[bot] commented 1 year ago

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

timmyhoa commented 1 year ago

Any solution?

Br3nda commented 11 months ago

does Preload of polymorphic work at all?

nghiadanggeocomply commented 5 months ago

Any idea for this?

duxphp commented 4 months ago

Unsolvable, feel free to try other orm or manual splicing