I have the following structs generated by Gorm Gen:
type UserBase struct {
ID int32 `gorm:"column:id;primaryKey;autoIncrement:true" json:"id"`
Name string `gorm:"column:name" json:"name"`
}
type AccountBase struct {
ID int32 `gorm:"column:id;primaryKey;autoIncrement:true" json:"id"`
Name string `gorm:"column:name" json:"name"`
}
I extend the UserBase struct to have a many to many relationship with AccountBase, for pre-loading and migration purposes:
type User struct {
UserBase
Accounts []AccountBase `gorm:"many2many:user_accounts"`
}
When I try and migrate the database to a clean MySQL database with not tables:
models := []interface{}{
&AccountBase{},
&User{},
}
for _, model := range models {
if err := db.Migrator().AutoMigrate(model); err != nil {
fmt.Printf("Error migrating model %v: %vn", model, err)
}
}
I get the following error:
Error 1215 (HY000): Cannot add foreign key constraint
[11.180ms] [rows:0] CREATE TABLE `user_account` (`user_id` int,`account_id` bigint unsigned,
PRIMARY KEY (`user_id`,`account_id`),CONSTRAINT `fk_user_account_user`
FOREIGN KEY (`user_id`) REFERENCES `user`(`id`),
CONSTRAINT `fk_user_account_account`
FOREIGN KEY (`account_id`) REFERENCES `account`(`id`))
Error migrating model &{{0 } []}: Error 1215 (HY000): Cannot add foreign key constraint
Notice that when it infers the many to many table, it creates the account_id field as a bigint unsigned, which does not match the ID field in the account table, since it was generated matching the structs int32 declaration.
Why is is creating that account_id field in the joining table as the wrong type? Also, why is it then creating the user_id field in the many to many table as the correct int type? Both ID fields are declared in the same way in the corresponding structs.