0

I'm working on a Gin app with Gorm. Currently, I've got the following struct which represents a 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 in fact created, but not with the specified constraints. Inspecting the table's DDL, here's how it is being 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 am I doing wrong?

1 Answer 1

2

Based on the doc, I believe you should use semicolon (;) instead comma (,) between tag constraints declaration

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
}
5
  • 1
    my bad, that was indeed the issue. I appreciate your help.
    – MrCujo
    Apr 18, 2022 at 18:41
  • how to use unsigned?
    – Nux
    Apr 24, 2022 at 14:57
  • @Nux sorry, what exactly do you mean with how to use unsigned?
    – MrCujo
    Apr 30, 2022 at 3:20
  • I want interger type stored in db to be unsigned. -23 is signed and 23 is unsigned. Right now it is possible to insert negative number in my column but that is not what I intend. TLDR: I mean SQL unsigned. So how it works with gorm?
    – Nux
    May 1, 2022 at 7:50
  • I asked a auestion here for more details. Have a look here stackoverflow.com/questions/71989945/…
    – Nux
    May 1, 2022 at 7:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.