[英]Golang Gorm not creating table with constraints
I'm working on a Gin app with Gorm.我正在使用 Gorm 开发 Gin 应用程序。 Currently, I've got the following struct which represents a model:目前,我有以下代表 model 的结构:
// Category represents a category object in the database
type Category struct {
Name string `json:"name" gorm:"size:60,unique,not null"`
Description string `json:"description" gorm:"size:120"`
Parent uint `json:"parent"`
Active bool `json:"active" gorm:"default:true"`
gorm.Model
}
as you can see, there are some constraints such as size
, unique
, and not null
.如您所见,有一些限制,例如size
、 unique
,而not null
。
When I run the migration db.AutoMigrate(&entities.Category{})
当我运行迁移db.AutoMigrate(&entities.Category{})
the table is in fact created, but not with the specified constraints.该表实际上已创建,但没有指定约束。 Inspecting the table's DDL, here's how it is being created:检查表的 DDL,下面是它的创建方式:
CREATE TABLE `categories` (
`name` longtext DEFAULT NULL,
`description` varchar(120) DEFAULT NULL,
`parent` int(10) unsigned DEFAULT NULL,
`active` tinyint(1) DEFAULT 1,
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`created_at` datetime DEFAULT NULL,
`updated_at` datetime DEFAULT NULL,
`deleted_at` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `idx_categories_deleted_at` (`deleted_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
any idea what am I doing wrong?知道我做错了什么吗?
Based on the doc , I believe you should use semicolon ( ;
) instead comma ( ,
) between tag constraints declaration根据文档,我认为您应该在标记约束声明之间使用分号 ( ;
) 而不是逗号 ( ,
)
type Category struct {
Name string `json:"name" gorm:"size:60;unique;not null"`
Description string `json:"description" gorm:"size:120"`
Parent uint `json:"parent"`
Active bool `json:"active" gorm:"default:true"`
gorm.Model
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.