golang gin gorm вставить и установить primary_key, но primary_key получил null

Я использую приложение сборки gin gorm mysql.

Я установил topic_id primary_key auto_increment не равным null в model.go следующим образом:

type Topic struct {
    gorm.Model
    TopicId    uint64 `gorm:"PRIMARY_KEY;AUTO_INCREMENT;NOT NULL"`
    TopicName  string
    TopicDesc  string
    OwnerId    int
    CreateIP   string
    CreateTime uint64
    UpdateTime uint64
}

создать тему в service.go

type TopicCreateService struct{
    TopicName string `form:"topic_name" json:"topic_name" binding:"required,min=1,max=30"`
    TopicDesc string `form:"topic_desc" json:"topic_desc" binding:"required,min=1,max=300"`
    OwnerId int `form:"owner_id" json:"owner_id" binding:"required,min=1,max=30"`
}

func (service *TopicCreateService) Create(c *gin.Context) serializer.Response{
    topic := model.Topic{
        TopicName:service.TopicName,
        TopicDesc:service.TopicDesc,
        OwnerId:service.OwnerId,
        CreateIP:c.ClientIP(),
        CreateTime:uint64(time.Now().UnixNano()),
        UpdateTime:0,
    }

    if err:=model.DB.Create(&topic).Error;err!=nil{
        return serializer.ParamErr("创建话题失败", err)
    }
    return serializer.BuildTopicResponse(topic)
}

введите здесь описание изображения

Я хочу, чтобы topic_id был моим primary_key, а не нулевым автоинкрементом. Что не так?


person 齐德隆咚锵    schedule 02.04.2020    source источник
comment
с этим кодом ----- TopicId uint64 gorm:"PRIMARY_KEY;AUTO_INCREMENT;NOT NULL" db.AutoMigrate даже не работает   -  person 齐德隆咚锵    schedule 02.04.2020


Ответы (2)


вы включили gorm.Model в свою структуру. Это означает, что миграция вашей модели / база данных выдаст ошибку:

Error 1075: Incorrect table definition; there can be only one auto column and it must be defined as a key

Если вы удалите gorm.Model из своей Topic структуры, все будет хорошо.

package model

import (
    `github.com/jinzhu/gorm`
)

type WithoutModel struct {
    MyId int64 `gorm:"primary_key;auto_increment;not_null"`
    Name string
}

func ModelSave(tx *gorm.DB) {
    wo := WithoutModel{Name:"Without the model"}
    tx.Save(&wo)
}

После нескольких запусков ModelSave у меня есть:

MariaDB [gmodel]> select * from without_models;
+-------+-------------------+
| my_id | name              |
+-------+-------------------+
|     1 | Without the model |
|     2 | Without the model |
+-------+-------------------+
2 rows in set (0.000 sec)
person craigmj    schedule 02.04.2020

gorm.Model 
// gorm.Model 定义
type Model struct {
  ID        uint `gorm:"primary_key"`
  CreatedAt time.Time
  UpdatedAt time.Time
  DeletedAt *time.Time
}

общие правила

person 齐德隆咚锵    schedule 29.07.2020