我正在與 Gorm 一起開發(fā) Gin 應(yīng)用程序。目前,我有以下代表模型的結(jié)構(gòu):
// 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
。
當(dāng)我運行遷移時
db.AutoMigrate(&entities.Category{})
該表實際上已創(chuàng)建,但沒有指定約束。 檢查表的 DDL,以下是它的創(chuàng)建方式:
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;
知道我做錯了什么嗎?
根據(jù)doc,我相信您應(yīng)該使用分號(;
)標(biāo)簽約束聲明之間的逗號 (,
)
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 }