How to handle polymorphic queries in GORM

372 Views Asked by At

I currently have the following models set up:

type TextQuestion struct {
    gorm.Model
    Prompt  *Prompt             `gorm:"polymorphic:Question"`
}

type ChoiceQuestion struct {
    gorm.Model
    Prompt  *Prompt             `gorm:"polymorphic:Question"`
}

type Prompt struct {
    gorm.Model

    QuestionID   int    `gorm:"not null"`
    QuestionType string `gorm:"not null"`
}

I would like to get the question associated with a prompt and delete it, but how can that be done? The GORM docs only gives examples for how to create new entries, not querying or other operations.

Of course, I could use a switch statement and handle each QuestionType separately, like so:

switch prompt.QuestionType {
    case "choice_question":
        // ...
    case "text_question":
        // ...
    }

But that would defeat the purpose of polymorphism in the first place. Is there a more elegant way to handle polymorphic relationships?

0

There are 0 best solutions below