Home  >  Q&A  >  body text

Golang Gorm cannot create table with constraints

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粉418854048P粉418854048207 days ago451

reply all(1)I'll reply

  • P粉736935587

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

    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
    }
    

    reply
    0
  • Cancelreply