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 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘