Skip to content

How do you change which field/column in the base table is referenced by the foreign key of a sub table? #1936

Open
@darienmiller88

Description

@darienmiller88

I have two structs I'm currently trying to link via foreign key:

type Child struct{
	ID              int 		   `pg:",pk"`
	MyFK         int 
	CreatedAt time.Time 
	UpdatedAt time.Time 
	DeletedAt time.Time `pg:",soft_delete"`
 
	Base          Base	`pg:"fk:my_fk"`
}
type Base struct{
	ID 		               int `pg:",pk"`
	FieldToReference    int `pg:",unique"`
	CreatedAt               time.Time 
	UpdatedAt             time.Time 
	DeletedAt              time.Time `pg:",soft_delete"`
 }

I want the "MyFK" field of my child struct to reference the "FieldToReference" field of the base struct. How do I accomplish this? MyFK by default references the ID field instead of my target field.

Expected Behavior

The table to establish a foreign key bewteen MyFK and FieldToReference

Current Behavior

The table instead connects MyFK to ID,

Steps to Reproduce

type Child struct{
	ID              int 		   `pg:",pk"`
	MyFK         int 
	CreatedAt time.Time 
	UpdatedAt time.Time 
	DeletedAt time.Time `pg:",soft_delete"`
 
	Base          Base	`pg:"fk:my_fk"`
}

type Base struct{
	ID 		               int `pg:",pk"`
	FieldToReference    int `pg:",unique"`
	CreatedAt               time.Time 
	UpdatedAt             time.Time 
	DeletedAt              time.Time `pg:",soft_delete"`
 }

func main(){
          db.Model( &Base{}, &Child{}).CreateTable(&orm.CreateTableOptions{
		FKConstraints: true,
	})
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions