Your Question

https://github.com/go-gorm/playground/pull/628

type MyModel struct {
    Id        uint `gorm:"primaryKey"`
    CreatedBy uint
}

type User struct {
    MyModel
    Name string
}

type Store struct {
    MyModel
    Name     string
    Products []Product `gorm:"foreignKey:StoreId"`
}

type Product struct {
    MyModel
    StoreId uint
    Name    string
    OwnerId uint
    // Owner   User `gorm:"foreignKey:OwnerId;references:Id"` // this works
    Owner User `gorm:"foreignKey:CreatedBy;references:Id"` // this does't work, CreatedBy here should belong to Product, not User
}

The document you expected this should be explained

https://gorm.io/docs/belongs_to.html

Expected answer

According to the doc, User and Product have the same key CreatedBy, so references should be used. But it fails in my case. I'm wondering whether foreign key and references can be used together. Thank you in advanced!

Comment From: yiannisccmath

I had the same issue and I resolved it by changing the self referential property of the user to a different name, since this is the property that other models use twice. It somehow gets confused if you try to connect 2 properties that have same foreign key names.

So the result is

type User struct {
    ID              uint `gorm:"primaryKey"`
    CreatedByUserID uint
    CreatedByUser   *User `gorm:"foreignKey:CreatedByUserID"`
    Name            string
}

type MyModel struct {
    ID          uint `gorm:"primaryKey"`
    CreatedByID uint
    CreatedBy   *User `gorm:"foreignKey:CreatedByID"`
}

type Store struct {
    MyModel
    Name     string
    Products []Product `gorm:"foreignKey:StoreID"`
}

type Product struct {
    MyModel
    StoreID uint
    Name    string
    OwnerID uint
    Owner   *User `gorm:"foreignKey:OwnerID"`
}

Comment From: jinzhu

It doesn't work with the same field names, you have to use a different one for foreign keys.

btw, you can use gorm:"column:xxx" to rename a field's column name.