Marno vN
Marno vN

Reputation: 155

GORM not inserting foreign key with create

I am having issues with Go's GORM. When I am trying to save an entity to the DB with a model inside it, it does not save the foreign key with the owner model.

Below is my Models, The MySQL script and the way I save/create the model into the DB.

The error I am getting is: Field 'business_industry_id' doesn't have a default value

type Business struct {
    gorm.Model
    BusinessName       string     `json:"BusinessName"       binding:"required"  gorm:"column:business_name;type:varchar(100);unique;not null"`
    BusinessIndustry   Industry   `json:"BusinessIndustry"   binding:"required"  gorm:"foreignkey:id"`
} 

type Industry struct {
    gorm.Model
    Name string `json:"Name" gorm:"column:name;type:varchar(100);unique;not null"`
}
CREATE TABLE `industries`
(
    id         INT(6) AUTO_INCREMENT,
    name       VARCHAR(100) UNIQUE NOT NULL,
    created_at TIMESTAMP NOT NULL DEFAULT current_timestamp,
    deleted_at TIMESTAMP,
    updated_at TIMESTAMP,
    PRIMARY KEY (id)
);

CREATE TABLE `businesses`
(
    id                             INT(6) AUTO_INCREMENT,
    business_name                  VARCHAR(100) NOT NULL UNIQUE,
    business_industry_id           INT(6) NOT NULL,
    created_at TIMESTAMP           NOT NULL DEFAULT current_timestamp,
    deleted_at TIMESTAMP,
    updated_at TIMESTAMP,
    PRIMARY KEY (id),
    FOREIGN KEY (business_industry_id) REFERENCES industries (id)
);
err := bs.database.Create(business).Error

I tried remove the Grom attributes from the models, to let the framework figure it out on it's own, but I got the same error.

When I inspect the model, the industry have id of 3 (Because I resolved it earlier on myself) and after I do the save, the ID is 0. But when I removed the attributes, the id was 3 after the save as well, but the same error occurred.

I know what the error message mean, because the sql message that is logged, doesn't actually insert the 3 into the business_industry_id field. What I don't know is, why it doesn't insert it.

Upvotes: 0

Views: 4311

Answers (1)

dave
dave

Reputation: 64657

I'm fairly certain you have to include the foreign key, you can't just have the associated model (see http://gorm.io/docs/has_many.html). So you need to do:

type Business struct {
    gorm.Model
    BusinessName       string     `json:"BusinessName"       binding:"required"  gorm:"column:business_name;type:varchar(100);unique;not null"`
    BusinessIndustryID uint
    BusinessIndustry   Industry   `json:"BusinessIndustry"   binding:"required"  gorm:"foreignkey:id"`
} 

Upvotes: 2

Related Questions