Insert or update on table "TABLE_C" violates foreign key constraint "fk_table_c_table_b"

I have 3 tables in code 2 are child tables 1 is parent table.
when i am inerting data in Table C is throws below error
insert or update on table “TABLE_C” violates foreign key constraint “fk_table_c_table_b”

type TABLEA  struct {
	TableAId             int    `gorm:"primary_key;NOT NULL AUTO_INCREMENT"`
	UserName            string `gorm:"type:text;"`
	InsertedBy          int    `gorm:"type:int;"`
	InsertedDatatime    time.Time
	LastUpdatedBy       int `gorm:"type:int;"`
	LastUpdatedDatetime time.Time
}

 type TABLEB  struct {
	TableBId              int    `gorm:"primary_key;NOT NULL AUTO_INCREMENT"`
	UserName            string `gorm:"type:text;"`
	InsertedBy          int    `gorm:"type:int;"`
	InsertedDatatime    time.Time
	LastUpdatedBy       int `gorm:"type:int;"`
	LastUpdatedDatetime time.Time
}
type TABLEC struct {
	TableCId              int `gorm:"primaryKey;"`
	TableAId              int    `gorm:"type:int;"`
	TableBId              int `gorm:"type:int;"``
	InsertedBy            int `gorm:"type:int;"`
	InsertedDatetime           time.Time
	LastUpdatedBy         int `gorm:"type:int;"`
	LastUpdatedDatetime   time.Time
	TableA                        TableA       `gorm:"foreignKey:TableAId;references:TableAId;"`
	TableB                        TableB       `gorm:"foreignKey:TableBId ;references:TableBId;"`
}

 data:= TableCDetails{
		TableA:                           tableAModel,
		TableB:                           tableBModel,
		InsertedBy:                       user_id,
		InsertedDatetime:                    time.Now(),
		LastUpdatedDatetime:                 time.Now(),
	}

if err := DB.Create(data).Error; err != nil {
		return err
	}

Hi @sumit-kapoor, welcome to the forum.

Try removing the space in the struct tag for TableB:

foreignKey:TableBId ;
// this one -------^

I don’t know about GORM specifically, but in general, spaces can be relevant in struct tags. Hence, GORM might take that space as part of the value.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.