LoginSignup
8
5

More than 5 years have passed since last update.

GORM で AUTO_INCREMENT でないプライマリキーを作成する

Posted at

GORM ではプライマリキーが int だと自動的に AUTO_INCREMENT が付与されます。
以下は MySQL での例です。

type Users struct {
    UserID int `gorm:"primary_key"`
}
db.AutoMigrate(Users)  // CREATE TABLE `users` (`user_id` int AUTO_INCREMENT , PRIMARY KEY (`user_id`))

AUTO_INCREMENT にしたくないときは struct tag で明示的にカラムタイプを指定します。

type Users struct {
    UserID int `sql:"type:int" gorm:"primary_key"`
}
db.AutoMigrate(Users)  // CREATE TABLE `users` (`user_id` int , PRIMARY KEY (`user_id`))

参考情報

8
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
5