Golang Gorm cannot create table with constraints
P粉418854048
P粉418854048 2024-03-26 11:35:13
0
1
561

I'm developing a Gin application with Gorm. Currently, I have the following structure representing the 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.

When I run the migration db.AutoMigrate(&entities.Category{})

The table is actually created, but no constraints are specified. Check the DDL for the table, here's how it was created:

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 I did wrong?

P粉418854048
P粉418854048

reply all(1)
P粉736935587

According to doc, I believe you should use semicolon (;) tags to constrain commas between declarations (,)

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
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template