Reputation: 155
I am having issues with Go's Gorm.
I have a table called scopes and a table called employees. I also have a many2many/intermediary table called employee_scopes.
When I am trying to save the employee with the specified scopes. I get an an error that Gorm is trying to insert the record into the intermediary table as if it was the scopes table.
Error Message: Error 1054: Unknown column 'scope' in 'field list'
Models:
type Employee struct {
gorm.Model
FirstName string `json:"FirstName" gorm:"column:first_name;type:varchar(100);not null"`
Scopes []EmployeeScope `json:"Scopes" gorm:"many2many:employee_scopes"`
}
type EmployeeScope struct {
gorm.Model
Scope string `json:"Scope" `
}
SQL:
CREATE TABLE `employees`
(
ID INT(6) AUTO_INCREMENT,
first_name VARCHAR(100) NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT current_timestamp,
deleted_at TIMESTAMP,
updated_at TIMESTAMP,
PRIMARY KEY (id),
);
CREATE TABLE `scopes`
(
id INT(6) AUTO_INCREMENT,
scope VARCHAR(100) UNIQUE NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT current_timestamp,
deleted_at TIMESTAMP,
updated_at TIMESTAMP,
PRIMARY KEY (id)
);
CREATE TABLE `employee_scopes`
(
id INT(6) AUTO_INCREMENT,
employee_id INT(6) NOT NULL,
scope_id INT(6) NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT current_timestamp,
deleted_at TIMESTAMP,
updated_at TIMESTAMP,
PRIMARY KEY (id),
FOREIGN KEY (employee_id) REFERENCES employees (id),
FOREIGN KEY (scope_id) REFERENCES scopes (id)
);
It's like Gorm is not listening to what I am specifying. I tried to add the back-reference, with the correct specifier, and I get the same error. I also added the many 2 many overrides, but that also didn't work.
Upvotes: 0
Views: 324
Reputation: 18480
Error Message: Error 1054: Unknown column 'scope' in 'field list'
Because of gorm use Table name as the pluralized version of the struct name (Ref). Thats why gorm try to insert data into employee_scopes
table. Your EmployeeScope
struct name should be Scope
.
type Employee struct {
gorm.Model
FirstName string `json:"FirstName" gorm:"column:first_name;type:varchar(100);not null"`
Scopes []Scope `json:"Scopes" gorm:"many2many:employee_scopes"`
}
type Scope struct {
gorm.Model
Scope string `json:"Scope" `
}
Upvotes: 1