go-gorm / gorm

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

Foreign Key gets set for one table but doesn't set for another #4477

Closed 20Aditya closed 3 years ago

20Aditya commented 3 years ago

Your Question

I have 2 tables GotestBusinessEntity and StatusBusinessEntity

GotestBusinessEntity looks like this:

type GotestBusinessEntity struct {
    Id                        *string `gorm:"primary_key"`
    Name                      *string
    Qtype                     *string
    ExternalBusinessObjectId1 *int32
    ExternalBusinessObjectId2 *string
    StatusBusinessEntityUid   *uint32               `gorm:"foreignKey:uid;constraint:OnUpdate:CASCADE,OnDelete:SET NULL;"`
    Status                    *StatusBusinesEntity  `gorm:"foreignKey:StatusBusinessEntityUid;association_foreignkey:StatusBusinessEntityUid;constraint:OnUpdate:CASCADE,OnDelete:SET NULL;"`
    StatusHistory             []StatusBusinesEntity `gorm:"foreignKey:uid;constraint:OnUpdate:CASCADE,OnDelete:SET NULL;"`
}

While StatusBusinessEntity looks like this:

type StatusBusinesEntity struct {
    Uid                    uint32 `gorm:"primaryKey"`
    Value                  *string
    StartDate              *time.Time
    EndDate                *time.Time
    GotestBusinessEntityID *string `gorm:"foreignKey:id;association_foreignkey:Uid;constraint:OnUpdate:CASCADE,OnDelete:SET NULL;"`
}

What's expected

GotestBusinessEntity has one-many relationship with StatusBusinessEntity.

StatusBusinessEntityUid field stores the current status uid of the entity

I insert my data like this:

func (db *DBClient) Save(entity *model.GotestBusinessEntity) error {

    jso, _ := json.Marshal(entity)
    fmt.Println(string(jso))

    db.Db.Omit("StatusHistory").Create(entity)
    return nil
}

The Issue

StatusBusinessEntityUid gets updated but GotestBusinessEntityID foreign key doesn't get Updated. It shows null.

gotest2 status2

What is the reason behind this??

github-actions[bot] commented 3 years ago

This issue has been automatically marked as stale because it has been open 60 days with no activity. Remove stale label or comment or this will be closed in 30 days