suchen

Heim  >  Fragen und Antworten  >  Hauptteil

Golang Gorm kann keine Tabelle mit Einschränkungen erstellen

Ich entwickle mit Gorm eine Gin-Anwendung. Derzeit habe ich die folgende Struktur, die das Modell darstellt:

// 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
}

Wie Sie sehen, gibt es einige Einschränkungen wie sizeuniquenot null.

Wenn ich die Migration durchführe db.AutoMigrate(&entities.Category{})

Die Tabelle wird tatsächlich erstellt, es sind jedoch keine Einschränkungen angegeben. Überprüfen Sie die DDL auf die Tabelle. So wird sie erstellt:

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;

Irgendeine Idee, was ich falsch gemacht habe?

P粉418854048P粉418854048312 Tage vor542

Antworte allen(1)Ich werde antworten

  • 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
    }
    

    Antwort
    0
  • StornierenAntwort