首頁  >  問答  >  主體

Golang Gorm無法建立帶有約束的表格

我正在與 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
}

如您所見,存在一些約束,例如 sizeuniquenot 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;

知道我做錯了什麼嗎?

P粉418854048P粉418854048207 天前454

全部回覆(1)我來回復

  • P粉736935587

    P粉7369355872024-03-27 09:18:07

    根據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
    }
    

    回覆
    0
  • 取消回覆