golang gin gorm insert and set primary_key but primary_key got null

齐德隆咚锵 :

I use gin gorm mysql build application.

I set topic_id primary_key auto_increment not null in model.go as follow:

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
}

create topic in 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)
}

enter image description here

i want topic_id be my primary_key and not null auto-increment. what`s wrong

craigmj :

you've included gorm.Model in your struct. This means that your model migration/database will give an error:

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

If you remove the gorm.Model from your Topic struct, you will be good.

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)
}

After running ModelSave a couple of times, I have:

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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=401705&siteId=1