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.
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"`
}
Related
In GORM, does AutoMigration() also give the NOT NULL attribute on the database side?
Thanks in advance
The answer is: No
So if you do not define not null (using GORM field tags) to that particular field, GORM will not add NOT NULL constraint to the field on db side. Except for the primary key. By default, PK will be defined as NOT NULL field.
Way to define the field as NOT NULL in GORM:
type User struct {
...
Email string `gorm:"not null"` // NOT NULL
...
}
For more, see official documentation of GORM: Field Tags
Gorm have a strange bug when i'm unable to use automatic table creation. If i use same primary key field name as referenced foreign key from other table, it can't handle it properly.
Working example - User.ComID references to Company.ID:
type User struct {
gorm.Model
ComID string
Company Company `gorm:"foreignKey:ComID;references:ID"`
}
type Company struct {
ID string `gorm:"primaryKey"`
}
produces followin auto-migration sequence with:
CREATE TABLE "companies" ("id" text,"name" text,PRIMARY KEY ("id"))
CREATE TABLE "users" ("id" bigserial,"created_at" timestamptz,"updated_at" timestamptz,"deleted_at" timestamptz,"name" text,"com_id" text,PRIMARY KEY ("id"),CONSTRAINT "fk_users_company" FOREIGN KEY ("com_id") REFERENCES "companies"("id"))
but if i change ID of second table to ComID
type User struct {
ComID string
Company Company `gorm:"foreignKey:ComID;references:ComID"`
}
type Company struct {
ComID string `gorm:"primaryKey"`
}
everything stops working. Gorm try to execute incorrect sql code, table users does not exists at that moment.
CREATE TABLE "companies" ("com_id" text,"name" text,PRIMARY KEY ("com_id"),CONSTRAINT "fk_users_company" FOREIGN KEY ("com_id") REFERENCES "users"("com_id"))
Any ideas how i can supply gorm with correct description (except creating different column names)?
If it matters, the dialect of sql is Postgres in this case.
gorm don't allow it:
references include self fields
you can change the code: relationship.go line 559
if ref.OwnPrimaryKey {
constraint.Schema = ref.ForeignKey.Schema
constraint.ReferenceSchema = rel.Schema
} else {
constraint.Schema = rel.Schema
constraint.ReferenceSchema = ref.PrimaryKey.Schema
}
to
if false {
constraint.Schema = ref.ForeignKey.Schema
constraint.ReferenceSchema = rel.Schema
} else {
constraint.Schema = rel.Schema
constraint.ReferenceSchema = ref.PrimaryKey.Schema
}
and if you run
db.Debug().AutoMigrate(User{})
you will see it:
CREATE TABLE "companies" ("com_id" text,"name" text,PRIMARY KEY ("com_id"),CONSTRAINT "fk_users_company" FOREIGN KEY ("com_id") REFERENCES "users"("com_id"))
I am trying to retrieve the information of an author based on a field in BookData that is not a primary key. Below you can see I have AuthorId in my BookData table and I am trying to get the author based on that AuthorId even though it is not the primary key. It seems GORM does not support this type of join, is there a way to do this?
You can also see below that I am able to properly get the PublisherProperty information because it's foreign key is BookData's primary key. I am just wondering how to do it if it not the primary key. Thanks in advance!
type BookData struct {
Id string `gorm:"primary_key;column:book_id"`
AuthorId string `gorm:"column:author_id"`
Author AuthorData `gorm:"foreignkey:AuthorId"`
PublisherProperty []PublisherProperty `gorm:"foreignkey:Id"`
}
type AuthorData struct {
Id string `gorm:"primary_key;column:author_id"`
Name string `gorm:"column:author_name"`
}
type PublisherProperty struct {
Id string `gorm:"primary_key;column:book_id"`
PublisherId string `gorm:"primary_key;column:publisher_id"`
PublisherTxt string `gorm:"column:publisher_txt"`
}
I am new to Spring Boot and Vaadin. I followed a tutorial to create CRUD pages for a phone book application however I am having trouble using foreign keys. I have a Contact table which has phone type (i.e. cell or home) as a foreign key - i.e. it is referenced to my PhoneType table. I am stuck on how to populate the phone type from a drop down of values populated in my PhoneType table. Right now I am I have the following member variable in my Contact class
#ManyToOne
#JoinColumn(name="type")
private PhoneType phoneType;
And in my PhoneType class I have
#Column(name = "type")
private String phoneType;
However I am getting an error that says "Error executing DDL via JDBC Statement".
The rest of the application works well with the CRUD pages.
Firstly in mySQL implementations you can't store actual objects unless you use 8.0+ JSON data type. SQL has no idea what a PhoneType is because it's an object and not a valid data type. https://www.w3schools.com/sql/sql_datatypes.asp
If you want to store actual objects you need to find a noSQL implementation that you like.
So your "Customer" class doesn't map to a table properly. You would need to make instance variables such as
String hasCellPhone, hasHomePhone; //etc for the options in your dropdown menu
instead of trying to put a phonetype object.
I asked almost the exact same question, I suggest you read this entire thread.
https://stackoverflow.com/a/50879597/5468597
create table item (
barcode bigint not null auto_increment primary key,
name varchar(20) not null,
type varchar(20) not null,
is_available boolean not null,
is_late boolean null,
notes varchar(255) null,
check_out_date datetime null,
due_date datetime null
#create index idx_barcode (barcode));
create table patron (
trinity_id bigint not null primary key,
name varchar(30) not null,
email varchar(20) not null,
owes_fines boolean not null,
fines_owed int null
#create index idx_trinity_id (trinity_id));
create table checked_out_items (
ref_id bigint primary key auto_increment not null,
patron_id bigint not null,
item_id bigint not null,
item_available boolean not null,
item_check_out_date datetime null,
item_due_date datetime null);
alter table checked_out_items
add constraint fk_patron_id
foreign key (patron_id) references patron(trinity_id),
add constraint fk_item_id
foreign key (item_id) references item(barcode)
#add constraint fk_item_available
#add constraint fk_check_out_date
#add constraint fk_due_date
#foreign key (item_available references item(is_available)
#foreign key (item_check_out_date) references item(check_out_date)
#foreign key (item_due_date) references item(due_date)
on update cascade
on delete cascade;
insert into patron values(0000000,'Test Erino','test#erino.edu',0,null);
insert into item values(1,'Chromebook','Laptop',0,null,null,null,null);
insert into checked_out_items(patron_id,item_id,item_available,item_check_out_date,item_due_date)
select patron.trinity_id,item.barcode,item.is_available,item.check_out_date,item.due_date
from patron
inner join item;
and lastly:
select * from item;
select * from patron;
select * from checked_out_items;
I won't post the java logic here. That's for you to read in the other thread.
I solved my question.
#ManyToOne (cascade = {CascadeType.ALL})
#JoinColumn(name="phoneType_typeId")
private PhoneType phoneType;
And
#Id
#GeneratedValue
#Column(name = "typeId")
private Long id;
I am creating a component for Joomla! 2.5 and I have the following MySQL table structure.
CREATE TABLE `#__table_a` (
id INT NOT NULL AUTO_INCREMENT,
actividad VARCHAR( 255 ),
publish_up DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
publish_down DATETIME NOT NULL
);
CREATE TABLE `#__table_b` (
id INT NOT NULL AUTO_INCREMENT,
table_a_id INT NOT NULL, /*foreign key to table '#__table_a' field 'id'*/
hora TIME NOT NULL,
created DATETIME NOT NULL,
publish_up DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
publish_down DATETIME NOT NULL
);
What I want is that, in the form where I managed data from "# __table_a", I need to be able to manage data that is listed in the table "#__table_b".
How do I do it?,
Ie where do I do the "query" for such data and to display them in the form?, in the "table_a" model or controller?