I have a Stack
which has many StackRequiredParameter
.
The StackRequiredParameter
is identified by its name but multiple stacks can have parameters of the same name. Therefore the PK is a composite of its name and the id of the stack which it belongs to.
type StackRequiredParameter struct {
ID string `gorm:"uniqueIndex:idx_required_id_unique_per_stack"`
StackID uint `gorm:"uniqueIndex:idx_required_id_unique_per_stack"`
}
I've tried to implement the Stack
as shown below.
type Stack struct {
gorm.Model
Name string `gorm:"unique"`
RequiredParameters []StackRequiredParameter `gorm:"foreignKey:ID,StackID; references:ID; constraint:OnUpdate:CASCADE,OnDelete:CASCADE" json:"requiredParameters,omitempty"`
}
But the above returns the following error
panic: runtime error: index out of range [1] with length 1
I'm pretty sure I get that error because I'm trying to match a composite key (ID, StackID) with just the ID of the stack. But please let me know if I'm not posting enough information here.
The problem is though, I'm not sure how to do it differently.
CodePudding user response:
The problem is both foreign key and references should contain equal columns
type Stack struct {
gorm.Model
Name string `gorm:"unique"`
RequiredParameters []StackRequiredParameter `gorm:"many2many:required_stack_parameters_joins; foreignKey:ID; joinForeignKey:StackID; References:Name; joinReferences:ParameterID; constraint:OnUpdate:CASCADE,OnDelete:CASCADE" json:"requiredParameters,omitempty"`
}
type StackRequiredParameter struct {
Name string `gorm:"primaryKey"`
}