I'm building a Golang backend using jinzhu/gorm and I'm having some troubles trying to set up a relation between two tables e.g. Items and Manufacturers using a foreign key.
I'm following the steps at jinzhu.me/gorm/models but I'm honestly finding myself puzzled coming from a more straightforward approach of manually writing tables etc, for instance, using go pq.
item.go:
package model
import "github.com/jinzhu/gorm"
type Item struct {
gorm.Model
Item string `gorm:"primary_key"`
Manufacturer Manufacturer `gorm:"ForeignKey:Name"`
}
manufacturer.go:
package model
import "github.com/jinzhu/gorm"
type Manufacturer struct {
gorm.Model
Name string `gorm:"primary_key"`
}
I get no errors nor warnings. Inspecting my tables I noticed no correlation was created. Item does not have Manufacturer field.
What I tried so far:
- Not explicitly writing
gorm:"ForeignKey:Name"
sinceManufacturer
field is already aManufacturer
- Writing
gorm:"ForeignKey:Name;AssociationForeignKey:Name"
- Manually associating them with
db.Model(&model.Item{}).Related(&model.Manufacturer{})
- Manually associating them with
db.Model(&model.Item{}).Related(&model.Manufacturer{}, "Manufacturer")
- Manually associating them with
db.Model("items").Related("manufacturers")
. They get created with this name on Postgresql even though their model's name is singular.
EDIT:
Trying something like
type Item struct {
Item string `gorm:"primary_key"`
Manufacturer Manufacturer
ManufacturerID int
}
type Manufacturer struct {
ID uint
Name string
}
Leads to the same result. No foreign key is created and I'm able to insert new items with a non-existent Manufacturer
.
What Am I doing wrong? Am I missing something?