go-gorm / gorm

The fantastic ORM library for Golang, aims to be developer friendly
https://gorm.io
MIT License
36.9k stars 3.93k forks source link

HasMany: ForeignKey as String #5924

Closed maltegrosse closed 1 year ago

maltegrosse commented 1 year ago

Your Question

Is it possible to use a String as a specific ForeignKey ? Using PostgreSQL Adapter

https://gorm.io/docs/has_many.html offers the possibility to change the default foreignKey.

Example:

type  A struct{
    Id int64 `gorm:"primaryKey"`
    Bs []B `gorm:"foreignKey:MyID"`

}
type  B struct{
    MyID string `gorm:"primaryKey"`

}
...
var models =  []interface{}{A{},B{}}
db.AutoMigrate(models...)

Create on postgres db level:

Expected answer

The primary key of B should be a String as defined in the gorm syntax.... Or am I doing something wrong?

P.S. Is this related to https://github.com/go-gorm/postgres/pull/111

maltegrosse commented 1 year ago

solved it: B needs a int field for reference....

type  A struct{
    Id int64 `gorm:"primaryKey"`
    Bs []B `gorm:"foreignKey:RefID"`

}
type  B struct{
    MyID string `gorm:"primaryKey"`
    RefID int64

}