douguai6716 2017-10-11 20:53
浏览 149

无法使用Gorm Postgresql设置外键

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" since Manufacturer field is already a Manufacturer
  • 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?

  • 写回答

2条回答 默认 最新

  • dongnuo2879 2017-10-11 23:10
    关注

    You have to do something like:

    type Item struct {
        gorm.Model
        Item         string       `gorm:"primary_key"`
        ManufacturerName string   `sql:"type:varchar REFERENCES manufacturers(name)"`
        Manufacturer Manufacturer `gorm:"ForeignKey:ManufacturerName;AssociationForeignKey:Name`
    }
    

    To tell it to a) Use ManufacturerName as the foreign key, and B) use Name on the other table.

    Or you can just do:

    type Item struct {
        gorm.Model
        Item         string       `gorm:"primary_key"`
        ManufacturerID uint       `sql:"type:uint REFERENCES manufacturers(id)"`
        Manufacturer Manufacturer `gorm:"ForeignKey:Man;AssociationForeignKey:Name"`
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)