我正在与 Gorm 一起开发 Gin 应用程序。目前,我有以下代表模型的结构:
// 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
}
如您所见,存在一些约束,例如 size、unique 和 not null。
当我运行迁移时
db.AutoMigrate(&entities.Category{})
该表实际上已创建,但没有指定约束。 检查表的 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;
知道我做错了什么吗?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
根据doc,我相信您应该使用分号(
;)标签约束声明之间的逗号 (,)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 }